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

The PHP way

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 we will copy right now.

The JavaScript way

I’ll try to get closer the more that I can of the returns PHP gives us. 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, 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 is possible. But in the real project, regarding to its conventions (naming) especially if you use jQuery, you will probably have to rename all the $_GET occurences.

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

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

Your turn to play!

Other methods

Thanks to Twitter, I complete 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 this time.
    Thank you to Xavier Zalawa for that information.

Sources and useful links

Cet article est également disponible en : French