yesJames.com
ahuh… sure… what ever you say…


howto: GET a URL parameter in JavaScript

Posted in JavaScript,programming by james on February 11th, 2008

A useful little piece of JavaScript for retrieving a URL parameter (Query String) from your page. If a requested parameter doesn’t exist it will return an empty string rather than a NULL object. It will also handle the inclusion of anchor tags in the URL and exclude them from possible results.

e.g. http://www.yesjames.com/test.php?myparam=justatest
calling “gerURLParam(‘myparam’) will return “justatest”

function getURLParam(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var pattern = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(pattern);
  var aResult = regex.exec(window.location.href);
  if ( aResult == null ) {
    return "";
  } else {
    return aResult[1];
  }
}