Javascript GET URL parameters

Oct27
  • Share

Difficulty: ★★★☆☆

This Javascript function I’ve used a lot. Retrieve URL GET parameters with Javascript.
(For example:
http://www.theUrl.nl/script.html?parameterX=100&parameterY=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));

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.

Sandy on March 9th, 2011 at 7:02 PM

Hey Sandy, thanks for your tips! I will check this out.

Lee on March 11th, 2011 at 11:39 AM

Leave a comment