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

January 04, 2020 No comments QA JavaScript Query Param Vanilla JS

1. Introduction

Sometimes there is a need to get request path with full all query params in JavaScript code. The good news is we don't need to have any framework (like jQuery) to achieve that. In a simple vanilla code, we can get all set up parameters from the request.

2. Sample JavaScript function to retrieve query parameters

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)

3. Conclusion

In this article, we showcased how to get query parameters from JavaScript code. Parsing window.location attributes are all we need in that case, no additional JS frameworks are required.

{{ message }}

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