Monday, October 17, 2011

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];
}

you can use this method in your aspx page as:
var value = getQuerystring('yourkey');