Monday, June 6, 2011

JavaScript : Get querystring key's value for current page url.

Querystring is very most used technique to pass values across pages to manage web application state. All server-side programming languages like c#, vb.net, java etc 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.
JavaScript Function
function getQuerystring(urlkey, default_)
  {
     if (default_==null) default_="en";
        urlkey = urlkey.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regex = new RegExp("[\\?&]"+urlkey+"=([^&#]*)");
        var qs = regex.exec(window.location.href);
        if(qs == null)
           return default_;
        else
           return qs[1];
  }
How to use this function

var langauge_value = getQuerystring('lang');
This function will help to retrieve current value for lang key in querystring. Call to this function will return 'en'.

No comments:

Post a Comment