Tuesday, February 16, 2010

Get query string using javascript

The following javascript code snippet facilitates Javascript's built in regular expressions to retrieve value of the key. Optionally, you can specify a default value to return when key does not exist.

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

The getQuerystring function is simple to use. Let's say you have the following URL:

http://www.youtube.com/watch?v=Ywyw2YeOOPk&feature=featured

and you want to get the "v" querystring's value:

var id = getQuerystring('v');

The output of id will be Ywyw2YeOOPk

1 comment: