PHP's $_GET with Javascript

September 24, 2009

I recently had a need to access the GET parameters of a URL through javascript. Now, natively, there is no global $_GET variable in javascript like there is in PHP. So you have to just parse the query string of the URL and make your own.

Below I have created a standalone function that stores the GET parameters in key-value pairs, and makes them accessible through a global $_GET variable. Also, for vanity URL's, I've stored the paths into a separate global $_VAN variable.

/*!
 * GET URL Parsing
 * September 24, 2009
 * Corey Hart @ http://www.codenothing.com
 */
;(function(window){
var
	// Storage of param keys to values
	$_GET = window.$_GET = {},
	// Storage of vanity slices
	$_VAN = window.$_VAN = {},
	// Faster Referencing
	location = window.location,
	// Query String of the URL
	search = location.search,
	// Href for Vanity URL's
	href = location.href,

	/* Parsing */
	// Remove the '?'
	index = search.indexOf('?') != -1 ? search.indexOf('?') + 1 : 0,
	// Separate by ampersand
	get = search.substr(index).split('&'),
	// For vanity URL's, remove the host and store in array form split on the href's slash
	vanity = href.replace(/^https?:\/\/(.*?)\//i, '').replace(/\?.*$/i, '').split('/');

	// Loop through each key/value pair
	for (var i in get){
		var split = get[i].split('=');
		// Store non-value as a null instead of undefined to
		// differentiate between key existing and value existing
		$_GET[split[0]] = split[1]||null;
	}

	// Loop through hashed url for splitting
	for (var i in vanity)
		// Again, store non-value as a null instead of undefined
		$_VAN[i] = vanity[i]||null;
})(window);

If you have firebug installed, you can see the results of the vanity URL parsing. And if you add some GET Parameters to the page, the $_GET var will have content as well. Also, below, I've included the yui compressed version of the above function for all you minimalists. Enjoy.

/*
 * GET URL Parsing
 * September 24, 2009
 * Corey Hart @ http://www.codenothing.com
 */
;(function(f){var k=f.$_GET={},h=f.$_VAN={},j=f.location,l=j.search,a=j.href,e=l.indexOf("?")!=-1?l.indexOf("?")+1:0,b=l.substr(e).split("&"),c=a.replace(/^https?:\/\/(.*?)\//i,"").replace(/\?.*$/i,"").split("/");for(var d in b){var g=b[d].split("=");k[g[0]]=g[1]||null}for(var d in c){h[d]=c[d]||null}})(window);
Have a question or comment? ask@codenothing.com.