How to Retrieve GET URL Parameters Using JavaScript

Although it’s not something that needs to be done commonly, sometimes it can be very useful to be able to retrieve GET parameters from the URL of the current page using JavaScript.

To make life easier I have written a short piece of code that extends the "window.location" object to allow you to retrieve GET parameters using their key name

The Code:

// This function extends the window object so that it can
// retrieve and return the value of the named GET parameter
// Written by Aaron Gough: http://aarongough.com
window.location.keyValue = function ( keyName )
	{
	// Check to see if we have already retrieved the key value pairs
	// if we haven't then we need to retrieve them
	if( window.location.variablePairs == null )
		{
		if( window.location.href.indexOf('?') == -1)
			{
			return false;	
			}
		window.location.variablePairs = window.location.href.substr( window.location.href.indexOf('?') + 1).split('&');
		}
	
	// Search for the key that matches the keyName supplied
	for( var x = 0; x < window.location.variablePairs.length; x++ )
		{
		// If we find the key name then we retun the value associated with it
		if( keyName == window.location.variablePairs[x].substr( 0, window.location.variablePairs[x].indexOf('=')))
			{
			return window.location.variablePairs[x].substr( window.location.variablePairs[x].indexOf('=') + 1);
			}
		}
	
	// If we couldn't find the key in the GET parameters
	// then we return false
	return false;
	}

How to Use the Code:

Simply call the "window.location.keyValue" method like so:

var pageName = window.location.keyValue('page_name');