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.
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.
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(", "))
/*
* 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;
}