What is the best way to get query string values in Vanilla JS?

November 15, 2017 No comments QA JavaScript Query Param Vanilla JS

Sometimes we need to get request path with full query string in JavaScript. The good news are we don't need to have any framework (like jQuery) to achive this. In a simple vanilla code we can get all set up parameters from the request.

This simple function presented below: queryParam(queryParameter: string) reads search parameters from URL (window.location.search) and split them by parameter separator '&'.

In b variable you will have map that contains:

  • key - request parameter name,
  • value - request parameter value.
var queryParam = (function (a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i) {
        var p = a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

To get request parameter value simply call queryParam function with single attribute that will be your parameter name.

For URL with parameters like this: ?param1=val1&param2=query+string, function queryParam will return the following:

queryParam("param1"); // val1
queryParam("param2"); // query string
queryParam("other"); // undefined (object)
{{ message }}

{{ 'Comments are closed.' | trans }}