views:

223

answers:

3

When looking at location.search, what's the best way to take the query parameters and turn them into an object literal? Say I've got a URL that looks like this:

http://foo.com?nodeId=2&userId=3&sortOrder=name&sequence=asc

What I'd like to wind up with is an object literal that looks like this:

var params = {
  nodeId : 2,
  userId : 3,
  sortOrder: name,
  sequence: asc
}

So I'd like to do something like this:

var url = location.search;
url = url.replace('?', '');
var queries = url.split('&');
var params = {};
for(var q in queries) {
var param = queries[q].split('=');
params.param[0] = param[1];

};

But this line:

params.param[0] = param[1]

generates an error. How do you iterate through those keys if you don't know the key names?

We're using jQuery, and I'm sure there's a plugin to do this, but I'd like to understand how to program this anyway.

+1  A: 

You should use

params[ param[0] ] = param[1]

FYI, you could use a regex approach too.

seth
Doh! That's exactly what I was looking for. Thanks!
Pete
A: 

Get Query String Data with Javascript

function getQueryStrings() {
    var argList = {};

    if(window.location != null && window.location.search.length > 1) {
        var urlParms = window.location.search.substring(1);
        var argPairs = urlParms.split('&');

        for(var i = 0; i < argPairs.length; i++) {
            var pos = argPairs[i].indexOf('=')

            if(pos == -1)
                continue;
            else {
                var argName = argPairs[i].substring(0, pos);
                var argVal = argPairs[i].substring(pos + 1);

                if(argVal.indexOf('+') != -1)
                    argVal = argVal.replace(/\+/g, ' ');

                argList[argName] = unescape(argVal);
            }
        }
    }

    return argList;
}
Josh Stodola
Why didn't you use `.split('=')`? Why didn't you use `decodeURIComponent` (built for exactly this)?
Crescent Fresh
Because I am just a stupid pathetic programmer...?
Josh Stodola
Why the downvote? This is a legacy function. Don't ask *why*, just respect the fact that it has been production for years and it **works**.
Josh Stodola
A: 

Try the URL Utils jQuery plugin, it does precisely this!

var params = $.queryString();

Cowboy Ben Alman