Extracting Querystring key/value pairs in JavaScript

April 2009

Here's a quick and really easy one I post here primarily for my own benefit as I invariably forget the location.search syntax each time I need it.

Sometimes, particularly now in this AJAX "all in the browser" age, it is really useful to have client-side access to parameters passed to the page via the querystring. If you have access to a server side scripting language, it usually makes more sense for back-end of your application to handle this situation. In other cases though, we don't always have that luxury or it makes sense to do it a different way.

Here is a small function to extract those key/value pairs using JavaScript:

function ExtractQueryString() {
    var oResult = {};
    var aQueryString = (location.search.substr(1)).split("&");
    for (var i = 0; i < aQueryString.length; i++) {
        var aTemp = aQueryString[i].split("=");
        if (aTemp[1].length > 0) {
            oResult[aTemp[0]] = unescape(aTemp[1]);
    return oResult;

And here is some example usage:

var oData = ExtractQueryString();

In the above example, on a page called like so, http://yourdomain.com?name=Jon, the code would alert('Jon').

Jon Combe