Get URL Parameters (QueryStrings) using Javascript

Today I have got a request from a newbie .."How to get value from Querystring using Javascript in asp.net?" So I want to share with you ....

Unfortunately there is no method in JavaScript for parsing the querystring to get the value. So we try with regular expression to solve this problem..

JavaScript method for get URL parameter(QueryStrings)

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 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.

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

http://www.dotentboss.com?author=ahsan

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

var author_value = getQuerystring('author');

Comments

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Check/Uncheck all items in a CheckBoxList using Javascript