Wednesday, 23 September 2009

Get URL Querystring Parameters using Javascript

As we know in we can use Request.QueryString["variableName"] to retrieve the values of the variables in the HTTP query string. However if we need to get the parameter value in the client script, for instance we want to have an alert window to display a parameter value is not as straight forward as we do in server-side programming. Use the gup() helper function in JavaScript below can help us with this

function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
return results[1];

The way that the function is used is fairly simple. Let's say you have the following URL:


You want to get the value from the frank parameter so you call the javascript function as follows:

var name_param = gup( 'name' );

No comments:

Post a Comment