Javascript GET URL parameters
Oct27Difficulty: 




This Javascript function I’ve used a lot. Retrieve URL GET parameters with Javascript.
(For example:
http://www.theUrl.nl/script.html?parameterX=100¶meterY=200)
/**
* Get URL parameters
* @param the name of the parameter from the URL to retrieve
* @return the requested parameter value if exists else an empty string
*/
function getUrlParam(name) {
var regexS;
var regexl;
var results;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
regexS = "[\\?&]"+name+"=([^&#]*)";
regex = new RegExp(regexS);
results = regex.exec (window.location.href);
//note: don't write space after command exec
if ( results == null ) {
return "";
} else {
return results[1];
}
}
To show you the example with the previous given URL:
/* this will output the string 200, in an alert popup box */ alert(getUrlParam(parameterY));
Posted in javascript |get, / javascript, / URL, / url parameters
» 2 Comments, post your comment now. »
2 Responses to “Javascript GET URL parameters”
I like the idea, but I think a better idea would be to put all of the parameters in a persistent object. This way, whenever you are trying to retrieve the value, you don’t have to run those twenty-two lines every time. Personally, I started using jPaq’s GET object after I saw Chris West’s example in JS Bin: http://jsbin.com/checkerboard/2 . The cool thing about jPaq is the fact that you can just download the functions and objects that you want, not the extra stuff that you will never use anyway.