Get URL parameter in javascript

Sometimes in javascript you have the variable that you need to use in the url, as a parameter passed in…

Novembre 25, 2010

Sometimes in javascript you have the variable that you need to use in the url, as a parameter passed in GET to the page, but you don’t have it in page. You can retrieve those data analyzing the window.location.href string. Here is the Javascript function that does the work, pass to it the variable name of the variable you need:

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

Another usefull function is the one that get the file name of the current page from the url.

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Comments on “Get URL parameter in javascript”

There are 2 thoughts

Comments are closed