JavaScript: Parse the Query String into a Usable Object

One common task when working in JavaScript on the client side is having to parse the query string into a usable object form.

Here’s a function that returns an array of arrays representing the key/value pairs in the query string:

 
// avoid naming collisions with a namespace
myNamespace = myNamespace || {};
 
// returns an array of arrays representing
// the key/value pairs in the querystring
myNamespace.getQueryStringLookup = function () {
    var queryString = location.search;
    if (!queryString || queryString.length < 2) {
        return [];
    }
 
    var queryStringKvps = location.search.slice(1).split('&', 100),
		lookup = [];
    for (var i = 0, imax = queryStringKvps.length; i < imax; i++) {
        var kvp = queryStringKvps[i].split('=', 2),
            key = kvp[0],
            value = decodeURIComponent(kvp[1]);
 
        if (!lookup[key]) {
            lookup[key] = [];
        }
 
        lookup[key].push(value);
    }
 
    return lookup;
};

So, for example, if you had a query string like the following:

?product=Apple&product=Orange&category=Fruit

You would get back an array that you could use as so:

 
var qsLookup = myNamespace.getQueryStringLookup();
 
var category = qsLookup["category"];
var products = qsLookup["product"];
var apple = products[0];
var orange = products[1];

Hope this helps.

This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *