up vote 0 down vote favorite

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.

flag

60% accept rate
What is your underlying HTML server, PHP, or something else? – mcandre Jul 6 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 Jul 6 at 17:32
you may want to accept the answer if it solved your problem: meta.stackoverflow.com/questions/5234/… – galambalazs Jul 11 at 15:20

2 Answers

up vote 3 down vote

[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(", "))​​
link|flag
1  
That regex fails if the URL has a named anchor. Might change [^&] to [^&#]. – Brock Adams Jul 8 at 4:05
Big thanks for the tip, I've updated the code and the url. :) – galambalazs Jul 8 at 9:39
up vote 0 down vote
/*
 * 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;
}
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.