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
Jeffrey
4,14612 gold badges45 silver badges67 bronze badges
-
What is your underlying HTML server, PHP, or something else?mcandre– mcandre2010年07月06日 17:06:31 +00:00Commented 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.Jeffrey– Jeffrey2010年07月06日 17:32:21 +00:00Commented Jul 6, 2010 at 17:32
2 Answers 2
[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
gblazex
50.3k12 gold badges100 silver badges92 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Brock Adams
That regex fails if the URL has a named anchor. Might change
[^&] to [^&#].gblazex
Big thanks for the tip, I've updated the code and the url. :)
Mike Purcell
Thx for the code snippet, used it here: stackoverflow.com/questions/15670317/…
/*
* 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
Anurag
142k37 gold badges223 silver badges262 bronze badges
Comments
lang-js