Geeks With Blogs
Phubar Baz Musings of an HTML5 Programmer

I find myself needing to get query parameters that are passed into a web app on the URL quite often. At first I wrote a function that creates an associative array (aka object) with all of the parameters as keys and returns it. But then I was looking at the revealing module pattern, a nice javascript design pattern designed to hide private functions, and came up with a way to do this without even calling a function.

What I came up with was this nice little object that automatically initializes itself into the same associative array that the function call did previously.

// Creates associative array (object) of query params
var QueryParameters = (function()
    var result = {};

    if (
        // split up the query string and store in an associative array
        var params ="&");
        for (var i = 0; i < params.length; i++)
            var tmp = params[i].split("=");
            result[tmp[0]] = unescape(tmp[1]);

    return result;

Now all you have to do to get the query parameters is just reference them from the QueryParameters object. There is no need to create a new object or call any function to initialize it.

var debug = (QueryParameters.debug === "true");


if (QueryParameters["debug"]) doSomeDebugging();

or loop through all of the parameters.

for (var param in QueryParameters) var value = QueryParameters[param];

Hope you find this object useful.

Posted on Monday, November 21, 2011 2:14 PM | Back to top

Comments on this post: Getting Query Parameters in Javascript

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © PhubarBaz | Powered by: