Also available in: Français

Seems to be really easy when you think about it. Though, during the same week, we questioned me two times about that. In a server language, getting the URL parameters is really easy. But JavaScript doesn’t offer a way to do it natively. I propose to you a little function to do so, but perhaps other ways exist already.

The PHP way to get Get Parameters

When parameter are in URL, PHP allows getting them easily.
Example with this URL: http://mydomain.tld/?name=geoffrey

<?php
	echo $_GET['name']; // display 'geoffrey'
?>

If several parameters are one after the other, we get somehting like that:
http://mydomain.tld/?name=geoffrey&age=42

<?php
	echo $_GET['name']; // display 'geoffrey'
	echo $_GET['age']; // display '42'
?>

It’s this behavior I want to mimic in JS.

The JavaScript way to get URL Parameters

I’ll try to get as close as I can to what PHP returns. In other words, if a parameter is declared a second time, I pick the last one. The param value is optional (the term just after the equal symbol) and will return an empty string.

function $_GET(param) {
	var vars = {};
	window.location.href.replace( location.hash, '' ).replace( 
		/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
		function( m, key, value ) { // callback
			vars[key] = value !== undefined ? value : '';
		}
	);

	if ( param ) {
		return vars[param] ? vars[param] : null;	
	}
	return vars;
}

With that JS function, you have two ways to do the work:

var name = $_GET('name'),
    age = $_GET('age');

or, the second one, more efficient:

var $_GET = $_GET(),
    name = $_GET['name'],
    age = $_GET['age'];

Of course, I played with the names of the function and variable, copying the $_GET name, just to show you that it’s possible. But in a real web project, regarding its conventions (naming) especially if you use jQuery, you will probably have to rename all the $_GET occurrences.

If you need to get more complexe values which could be encoded in the URI (for example, this parameter ?test=Hello, World!, use the decodeURI() function like that:

var deco_var = decodeURL( $_GET( 'test' ) );

Your turn to play!

Other methods to get URL Parameters in JS

Thanks to Twitter, and the time passing… I’ve completed this article with two other ways with the same goal:

  • window.location.search which allows you to access directly to everything found just after the “?” mark in the URL.
    Thank you to Nicolas Hoizey for that information.
  • URLSearchParams which has its own methods (get(), getAll(), etc.) but which is very experimental at the time of writing these lines.
    Thank you to Xavier Zalawa for that information.

Sources and useful links