Detect & manipulate URL parameters with JavaScript

Published by George; 07-Mar-2013, 10:28:45
Category: JavaScript
Revised: 02-Apr-2013, 23:20:04

It's often useful for developers to be able to detect URL parameters with JavaScript, but due to the nature of these entities it is sometimes a topic of confusion and frustration among JavaScript developers, particularly novice scripters, and also based on the fact that PHP is typically the language of choice when handling URL parameters by virtue of the $_POST and $_GET superglobals. JavaScript has no in-built functions or objects that can be used to pick out any or all URL parameters, but it does have the capability to grab the URL as a string, whereupon a developer can detect for the parameters themself.

If you're familiar with JavaScript then you may have seen the window.location object being used throughout other peoples' code examples or tutorials, but may not be aware of its abilities and how it can benefit you.

The location object has many objects and subroutines available (see a breakdown at W3Schools), but the one we're interested in here is the window.location.href object. This object simply returns the current URL in its entirety. Let's see some code:

/*
*	@param		string		parameter to return the value of.
*	@return		string		value of chosen parameter, if found.
*/
function get_param(return_this)
{
        // Globally replace illegal chars.
	return_this = return_this.replace(/\?/ig, "").replace(/=/ig, "");
        
        // Get the URL.
	var url = window.location.href;

        // Split by "param=value".
	var parameters = url.substring(url.indexOf("?") + 1).split("&");

        // Array to store individual values.
	var params = [];
	
	for(var i = 0; i < parameters.length; i++)
	    if(parameters[i].search(return_this + "=") != -1)
	        return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");

	return "Parameter not found";
}

function show_param()
{
        console.log(get_param("article"));
        console.log(get_param("category"));
}

I hope the comments suffice to explain the workings because I know that a long explanation is going to get confusing, despite the unsophisticated nature of the code. However, more clarifications need to be made.

First of all, URL parameters are typically detected using PHP because ordinarily a form is where URL parameters come from. If a user is submitting a form, it makes sense for PHP to be able to grab the data (for storage, e-mailing, etc.). However, there are times when parameters can be generated by the server or by dynamic links created in a web application, and it is useful to be able to grab them in JavaScript if you want client-side actions to be performed.

We can simulate parameters by submitting a form, then grab the parameters back from the URL. The following HTML code will achieve this:

<form id="form" method="GET"><input type="text" name="article" /> <input type="text" name="category" /> <input type="submit" value="Submit" />

The only thing left to do is add in some code to call the function, which will fully demonstrate the paramters have indeed been extracted from the URL.

<input onclick="javascript: show_param();" type="button" value="Get Params" />

Note that parameters words are generally seperated with underscores or hyphens, so adding in spaces will cause your parameters to have the "+" symbol added in their place.

If an array of parameters is required, a very similar function can be used to return everything at once:

/*
*	@return		array (parameter values).
*/
function get_params()
{
        // Get the URL.
	var url = window.location.href;

        // Split by "param=value".
	var parameters = url.substring(url.indexOf("?") + 1).split("&");

        // Array to store individual values.
	var params = [];
	
	// Loop through each parameter and extract the value. Store in params[i].
	for(var i = 0; i < parameters.length; i++)
	    params[i] = parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");

	return params;
}

Update: 03-April-2013

Some people have indicated that these methods of retrieving URL parameters are verbose and ugly or unnecessary, favouring a solution such as this one found on StackOverflow:

function getURLParameter(name) 
{
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

Certainly, this solution seems elegent and somewhat perplexing. However, there are some things wrong with this approach that I'd like to bring to your attention. First and foremost it's a regular expression solution, meaning if you don't understand regular expressions, you aren't going to know what is happening here. Secondly, it's also difficult to tell what's happening and how this function is working because of the multitude of clutter expressions such as these naturally contain. Therefore it takes longer to work with since solving the expression to some extent is required by the programmer before s/he can manipulate it. Thirdly, it's also inefficient and slow compared to my methods above.

I'm no code Nazi and a few milliseconds here or there doesn't bother me at all. If the code gets the job done without affecting the users security or experience, fine by me. However, my functions above will return results in under a millisecond in many cases, with the regular expression taking upto 20 milliseconds. That's 20 times slower in some cases. I know, who cares? It doesn't appear any slower or less efficient on the surface, but this is just another example of why regular expressions are not the be-all and end-all, and this is an over engineered solution to a basic task. Generally if a solution involving string manipulation is possible, it is nearly always more efficient and desirable than one that works with regular expressions.