How to get query parameters / string values from URL using JavaScript

17th February, 2021

Often when you use Javascript, there are at times you need to add some event listeners or execute some action based on the url structure. 

Here is a small snippet to get all the query parameters / strings as an Object of key/values.

 

function getUrlParameters()
{
    var out = {};
    var url_str = window.location.search.replace("?", "");
    var subs = url_str.split('&')
    for(var i = 0; i < subs.length; ++i)
    {
        var vals = subs[i].split('=');
        if (out[vals[0]] === undefined) {
            out[vals[0]] = vals[1];
        // If multiple params with same key
        } else if (Array.isArray(out[vals[0]])) {
            out[vals[0]].push(vals[1])
        } else {
            out[vals[0]] = [out[vals[0]], vals[1]]
        }
    }
    return out;
}

 

That's it. Use the above function for any url and in return you will get a dictionary.