How to retrieve all or specific get parameters from a URL with JavaScript

Have you ever worked in some frontend application and suddenly you need to modify some server side code, however you aren't able to modify it because you simply can't or you don't have the permission although it's necessary to do it? Nope ? We did, it's really a disaster, believe us. Not simply because you can't work as you want but because you can't get your things working in the right way. For example, according to the existence or value of a get parameter namely viewType in the URL, we'll show some element to the user in 2 different ways, that means that we'll render 2 types of views in the document and some view will hide when a specific view type is requested through a GET parameter in the URL.

This problem could be solved in the server side easily by adding a couple of if statements according to the viewType parameter in the request, however sometimes you are forced to check this in the view. It's worth to say that this project doesn't exists and it's a really exagerated example to help you understand what we're talking about.

If you really analized the logic of your project and there's not other way to do it, or you just simply need to access a GET parameter from the URL in the view for unknown reasons, then we'll show you how to it easily with JavaScript.

Geek note (maybe important)

Any of the methods on this article won't decode the + (plus) from a URL as all of them rely on the JavaScript function decodeURIComponent. There are a lot of websites that use the plus symbol as a space in the URL instead of its URL encoding representation %20 (even Google), however it should be only used for content with the type of response application/x-www-form-urlencoded. This is an interesting discussion theme between developers as it seems that you shouldn't use the plus symbol to represent a space in some GET parameter, however it makes the string really user friendly as it's easier to read with plus symbols.

We recommend you to read more about this discussion here in Stack Overflow.

Retrieve a single get parameter

Usually with a language server as PHP, you can easily retrieve a GET parameter and do something according to their value:

<?php

if (isset($_GET['parameter'])) {
    echo $_GET['parameter'];
}else{
    // Do other thing
}

But if you're forced or need to do it in the view, then there's no such a thing as a default function available in the browser to retrieve it. That means that you will need to build your own function to retrieve those values from the document.

To retrieve a single parameter from a URL in the document, we have 2 methods that you can use to do it:

A. Using a Regular Expression

The following _get function uses a regular expression to retrieve your get parameter and returns undefined in case that the parameter doesn't exist. It is written in 2 ways, the first allow you to do it directly from a document (the URL that will be used will be the current document location) and the second one expects the URL that will be processed as second argument:

/**
 * Function to retrieve a get parameter from the current document (using location.href)
 * 
 * @param parameter {String} Key of the get parameter to retrieve
 */
function _get(parameter) {
    var reg = new RegExp( '[?&]' + parameter + '=([^&#]*)', 'i' );
    var string = reg.exec(window.location.href);
    return string ? string[1] : undefined;
};

/**
 * Function to retrieve a get parameter from a String URL providen as second argument
 * 
 * @param parameter {String} Key of the get parameter to retrieve
 * @param URL {String} The URL to search for the get parameter
 */
function _get(parameter , URL) {
    var reg = new RegExp( '[?&]' + parameter + '=([^&#]*)', 'i' );
    var string = reg.exec(URL);
    return string ? string[1] : undefined;
};

And they can be used as follows:

// First method
// Current document URL = http://ourcodeworld.com/search?q=How%20are%20you
console.log(_get("q")); // How are you

// Second method
console.log(_get("q", "http://ourcodeworld.com/search?q=How%20are%20you"));// How are you

B. Splitting URL

If you don't like to use regular expressions because you don't understand them or think that they're slower than the plain manipulation of string, we'll show you another way to retrieve the get parameters from a URL by splitting it.

In the first method we'll search for the in the location.search string that returns all the query parameters on as string like ?q=12&otp=421. Then the string will be splitted by the & symbol that indicates that a new query parameter will be used. In the second parameter we'll split using the same method however with an entire URL providen as second argument:

/**
 * Retrieves the get parameter with the providen key in the current location of the document.
 * 
 * @param identifier {String} Key of the get parameter
 */
function _getParameter(identifier) {
    var result = undefined, tmp = [];

    var items = window.location.search.substr(1).split("&");

    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");

        if (tmp[0] === identifier){
            result = decodeURIComponent(tmp[1]);
        }
    }

    return result;
}

/**
 * Retrieves the get parameter with the providen key on the providen URL as second argument.
 * 
 * @param identifier {String} Key of the get parameter 
 * @param URL {String} The URL to process 
 */
function _getParameter(identifier , URL) {
    var result = null, tmp = [];

    var usefulParam = URL.split("?")[1] || "";
    var items = usefulParam.split("&");

    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");

        if (tmp[0] === identifier){
            result = decodeURIComponent(tmp[1]);
        }
    }

    return result;
}

They can be used as follows:

// First method
// Current document URL = http://ourcodeworld.com/search?q=How%20are%20you
console.log(_getParameter("q")); // How are you

// Second method
console.log(_getParameter("q", "http://ourcodeworld.com/search?q=How%20are%20you"));// How are you

Retrieve all get parameters

Although it would be more secure for your application to define which get parameters are expected as anyone can modify the get parameters from the URL, you can retrieve in a single object all the get parameters of a URL if you need to. As said, it's important that your code checks for specific query parameters instead of loop automatically through them.

The following snippet will declare an object in the window namely QueryString. In this object a new element will be declared for every GET parameter available in the URL (with the same key as the parameter). The second snippet is a function that does the same as the first but instead of declare it in the window allows you to be used as a function that returns the object into a variable:

/**
 * Declares a new object in the window namely QueryString that contains every get parameter from the current URL as a property
 */
window.QueryString = function () {
    // This function is anonymous, is executed immediately and 
    // the return value is assigned to QueryString!
    var query_string = {};
    var query = window.location.search.substring(1);
    var vars = query.split("&");

    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");

        // If first entry with this name
        if (typeof query_string[pair[0]] === "undefined") {
            query_string[pair[0]] = decodeURIComponent(pair[1]);
            // If second entry with this name
        } else if (typeof query_string[pair[0]] === "string") {
            var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
            query_string[pair[0]] = arr;
            // If third or later entry with this name
        } else {
            query_string[pair[0]].push(decodeURIComponent(pair[1]));
        }
    }

    return query_string;
}();


/**
 * This function returns an object that contains every get parameter from a URL (first argument) as a property
 * 
 * @param URL {String}
 */
function QueryString(URL) {
    // This function is anonymous, is executed immediately and 
    // the return value is assigned to QueryString!
    var query_string = {};
    var usefulParam = URL.split("?")[1] || "";
    var query = usefulParam || "";
    var vars = query.split("&");

    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        
        // If first entry with this name
        if (typeof query_string[pair[0]] === "undefined") {
            query_string[pair[0]] = decodeURIComponent(pair[1]);
            // If second entry with this name
        } else if (typeof query_string[pair[0]] === "string") {
            var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
            query_string[pair[0]] = arr;
            // If third or later entry with this name
        } else {
            query_string[pair[0]].push(decodeURIComponent(pair[1]));
        }
    }

    return query_string;
}

Imagine this object as the $_GET array of PHP, so you can simply access the key in the object and it case it doesn't exist it will simply be undefined:

// Current URL: https://www.google.de/?gfe_rd=cr&ei=JFkHWdqAFafPXq3goBA&gws_rd=ssl&q=Our+Code+World
QueryString["q"]; // Our+Code+World
QueryString["gfe_rd"]; // cr
QueryString["ei"]; //JFkHWdqAFafPXq3goBA
QueryString["gws_rd"]; // ssl

// {
//      "gfe_rd": "cr",
//      "ei": "JFkHWdqAFafPXq3goBA",
//      "gws_rd": "ssl",
//      "q": "Our+Code+World"
// }
var $_GET = QueryString("https://www.google.de/?gfe_rd=cr&ei=JFkHWdqAFafPXq3goBA&gws_rd=ssl&q=Our+Code+World");

Happy coding !

Become a more social person