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.

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(", "))​​
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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.