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 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.bloggingdeveloper.com?author=bloggingdeveloper
and you want to get the "author" querystring's value:
var author_value = getQuerystring('author');
Download querystring.js
If you execute code shown in the above line, the author_value will be bloggingdeveloper. The query string is parsed by the regular expression and the value of the author_value parameter is retrieved. The function is smart in a couple of ways. For example, if you have an anchor in your URL like our example URL above does (#top) the getQuerystring() function knows to stop before the # character. Also, if a requested parameter doesn't exist in the query string and the default value is not specified as a function parameter then an empty string is returned instead of a null.
Want automatic updates?
Subscribe to our RSS feed
or
Get Email Updates
sent directly to your inbox!
Currently rated 5.0 by 7 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5