Monday, August 3, 2009

Parse/Get QueryString with Client-Side 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_;
return qs[1];

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

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

var author_value = getQuerystring('author');

If you execute code shown in the above line, the author_value will be "microsoft". 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.
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments : on " Parse/Get QueryString with Client-Side JavaScript "