URL parameters with Javascript

So this took me by surprise the other day. JavaScript doesn’t have a function to retrieve a URL parameter value. i.e. There is no Request.Querystring command! Of course it wouldn’t start Request as it’s executing on the browser rather than the server but you would have thought there would be a built in command to do it.

After a bit of searching though I came across this script that does it:

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
  }
  return vars;
}

The function returns an array/object containing the parameters and their values. e.g. The following URL:

http://www.example.com/?Name=Tim&Sex=Male

Would return:

{
    "Name": "Tim",
    "Sex": "Male"
}

To use it in your code you would write

var name = getUrlVars()["Name"];

And that’s it

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s