Wednesday, August 25, 2010

                               

Monday, February 22, 2010

How to Parse a Query String in Javascript

For my first post, here is something I use frequently. I didn't happen to write this myself, but I use this on many pages and it works flawlessly.
This function will let you grab a variable from a query string, using Javascript to parse it.

How To Use: call the function getParameterByName( ) with the parameter of the name of your querystring variable.

IE:
Your url is:
http://url.com/index.html?myvar=abc
Calling the function with:
getParameterByName('myvar')
Will return the value of:
abc


The Code:

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