3

I've got an url like this:

http://www.somewhere.com/index.html?field[]=history&field[]=science&field[]=math

Using jQuery, how can I grab the GET array?

Thanks.

Brock Adams
94.1k23 gold badges243 silver badges313 bronze badges
asked Jul 6, 2010 at 17:02
2
  • What is your underlying HTML server, PHP, or something else? Commented Jul 6, 2010 at 17:06
  • server does PHP, I'm trying to filter a large table based on the jquery datatables filter... so I need to pass the array through jquery for the filter to work... if that makes sense. Commented Jul 6, 2010 at 17:32

2 Answers 2

6

[See it in action]

var str = "http://www.somewhere.com/index.html?field[]=history&field[]=science&field[]=math";
var match = str.match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
 var spl = match[i].split("=");
 var name = spl[0].replace("[]", "");
 var value = spl[1];
 obj[name] = obj[name] || [];
 obj[name].push(value);
}
alert(obj["field"].join(", "))​​
answered Jul 6, 2010 at 17:24
Sign up to request clarification or add additional context in comments.

3 Comments

That regex fails if the URL has a named anchor. Might change [^&] to [^&#].
Big thanks for the tip, I've updated the code and the url. :)
Thx for the code snippet, used it here: stackoverflow.com/questions/15670317/…
1
/*
 * Returns a map of querystring parameters
 * 
 * Keys of type <fieldName>[] will automatically be added to an array
 *
 * @param String url
 * @return Object parameters
 */
function getParams(url) {
 var regex = /([^=&?]+)=([^&#]*)/g, params = {}, parts, key, value;
 while((parts = regex.exec(url)) != null) {
 key = parts[1], value = parts[2];
 var isArray = /\[\]$/.test(key);
 if(isArray) {
 params[key] = params[key] || [];
 params[key].push(value);
 }
 else {
 params[key] = value;
 }
 }
 return params;
}
answered Jul 14, 2010 at 2:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.