Parse URL paramters into a JavaScript object

This function takes a URL with parameters and returns a JavaScript object with key/value pairs. If this function is called without a parameter it will use the current documents URL.

url = window.location

function getParameters(url) {
	var q = url ? url.search.substr(1) : window.location.search.substr(1),
	    res = {},
        tokens = [];
 
    tokens = q.split('&');
    for (var i = 0; i < tokens.length; i++ )
    {
        var param = tokens[i].split('=');
        res[param[0]] = param[1];
    }
    return res;
}

Example: http://domain.com?foo=bar&key=value

{
    foo: "bar",
    key: "value"
}

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>