Friday, March 23, 2012

Get URL Parameters (QueryStrings) using Javascript

function getQueryStringValue(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 getQueryStringValue function is simple to use. Let's say you have the following URL:
http://www.themoderneducation.com?YourName=TME
and you want to get the "YourName" querystring's value:
var YourName_Value = getQueryStringValue('YourName');
alert(YourName_Value); // Result = "TME"

No comments:

Post a Comment