Alvaro Dias

How to obtain query string values from JavaScript

The query string of the current URL can be obtained from the location object. This object can be accessed using the window.location property on the window object. It has all sorts of interesting properties that contain information of the current URL. The query portion of the URL is present in the search property (window.loction.search).

e.g. When I did a test search on bing, it redirected to the following URL: http://www.bing.com/search?q=test+search&go=&qs=n&form=QBLH&filt=all&pq=test+search&sc=0-0&sp=-1&sk=. In this, case window.location.search returns "?q=test+search&go=&qs=n&form=QBLH&filt=all&pq=test+search&sc=0-0&sp=-1&sk=".

Now, all that is left to be done is to parse this string to obtain the query parameters along with they values. One way to do this is to create and object with each parameter as a property as shown below **: -

// create an object that contains all query parameters
var rawParams = window.location.search.substr(1).split('&'),
    queryParams = {};
rawParams.forEach(function (v) {
    var temp = v.split('=');
    queryParams[temp[0]] = temp[1];
});

You could also create a function to get a specific value using something like below **.

function getParameterValue(name) {
    if (!queryParams) {
        var rawParams = window.location.search.substr(1).split('&');
        queryParams = {};
        rawParams.forEach(function (v) {
            var temp = v.split('=');
            queryParams[temp[0]] = decodeURIComponent(temp[1]);
        });
    }
    return queryParams[name];
}

** An important thing to note in the above code is that while the code outlines the logic to do this, you might want to harden it by doing things like add error handling and taking into consideration the + sign.

Links for futher reading on this topic: -