Friday, May 18, 2012

Get Querystring with JavaScript - Parse/Get QueryString with Client-Side JavaScript

Get URL Parameters (QueryStrings) using Javascript

Nearly all server-side programming languages have built-in functions to retrieve querystring values of a URL. In web browsers you can access the querystring with client-side JavaScript, but there is no standard way to parse out the name/value pairs. So here is a function to return a parameter you specify. 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 getmyQuerystring(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 getmyQuerystring function is simple to use. Let's say you have the following URL:


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

var author_value = getmyQuerystring (‘product’);

If you execute code shown in the above line, the product value will be SharePoint. The query string is parsed by the regular expression and the value of the product value parameter is retrieved. The function is smart in a couple of ways.

Thanks
Meera

No comments:

Post a Comment