Getting Query Parameters in Javascript

Posted by PhubarBaz on Geeks with Blogs See other posts from Geeks with Blogs or by PhubarBaz
Published on Mon, 21 Nov 2011 19:14:19 GMT Indexed on 2011/11/22 1:52 UTC
Read the original article Hit count: 610

Filed under:

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 (window.location.search)
    {
        // split up the query string and store in an associative array
        var params = window.location.search.slice(1).split("&");
        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");

or

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.

© Geeks with Blogs or respective owner