Get URL Parameter in Javascript

Just a useful little javascript function which will get a URL parameter and return it to you. For example if the current URL is “…?opendocument&id=testid” then calling getURLParam(“id”) will return “testid”.

function getURLParam(strParamName){
  var strReturn = “”;
  var strHref = window.location.href;
  if ( strHref.indexOf(“?”) > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf(“?”)).toLowerCase();
    var aQueryString = strQueryString.split(“&”);
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + “=”) > -1 ){
        var aParam = aQueryString[iParam].split(“=”);
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}

Update (31st December 2006)
This posting has been around for a long time now and gets a lot of traffic. Although it will still work fine as long as you know its limitations, several people have pointed to this article as being a better solution. I totally agree, it’s well worth a look.

Update (27th February 2007)
A couple of bug fixes raised via email. Thanks to Oliver Bryant for those.

Share