How to get URL request parameters into object literal?

When you look at location.search, what's the best way to take request parameters and turn them into an object literal? Let's say I have a url that looks like this:

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

What I would like to complete is an object literal that looks like this:

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

So, I would 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 over these keys if you don't know the key names?

We use jQuery, and I'm sure there is a plugin for this, but I would like to understand how to program this anyway.

+4
source share
2 answers

You have to use

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

FYI, you can use a regular approach .

+3
source

Try the Utils jQuery plugin URL , it does just that!

var params = $.queryString();

+1
source

All Articles