Accessing URL parameters in JavaScript

I have worked with PHP extensively and it is very convenient to have all the URL parameters automatically assigned to the global array $_GET. Here is an example:
$_GET['foo']; // bar

I wish JavaScript had a similar API but we since it doesn't we can create it. We can create a GET variable where we can access each parameter the same way as in PHP. Let's get started.

In JavaScript, all the URL parameters are available under the property. For some reason, it includes the question mark. Don't ask me why.

The plan is to separate each variable into its own property in an object saving them as key value using regex:

var GET = (function(){
    var get = {},
    // the add function turns a key into an
    // array if it is defined multiple times
    add = function (key,value){
        var cur = get[key];
        if (cur.isArray){
        }else {
            get[key] = [];
    search =,
    // decode special url characters like + into a (space)
    decode = function (s) {
        return decodeURIComponent(s.split("+").join(" "));

    // The dreaded Regex
    search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function (a,b,c) {
        var key = decode(b),
            value = decode(c);
        if (get[key]){
        }else {
            get[decode(b)] = decode(c);
    return get;

That's it! Now if you have a URL like this one: You can access the values like so:; // bar
GET.p1;  // value

You can also test the for values before using them:

var email;
// email was not defined in the URL
if ( { // undefined
    email =;
}else {
    email = "No Email";

Also an added feature is, if a parameter is defined twice it is automatically converted into an array.; // ["bar1","bar2"]

There now you can easily access your URL parameters


There are no comments added yet.

Let's hear your thoughts

For my eyes only