15

I have a form that uses the get method and contains an array:

http://www.example.com?name[]=hello&name[]=world

I'm trying to retrieve array values 'hello' and 'world' using JavaScript or jQuery.

I've had a look at similar solutions on Stack Overflow (e.g. How can I get query string values in JavaScript?) but they seem to only deal with parameters rather than arrays.

Is it possible to get array values?

4
  • 1
    The answer stackoverflow.com/a/3855394/295783 in the link you posted will work in your case too, unless the parms repeat as suggested by you mentioning array and the use of [] Commented Apr 7, 2013 at 17:56
  • 3
    Just to be clear: The URL does not have the concepts of arrays. All you have are multiple parameters with the same name. The [] are typically used for PHP servers, which will then created arrays out of these parameters. Other languages (e.g. Python) can handle multiple parameters with the same name (and without []) just fine. Commented Apr 7, 2013 at 17:56
  • 2
    From the question you linked to, you might find this answer helpful: stackoverflow.com/a/9362596/218196. Commented Apr 7, 2013 at 18:00
  • Okay thanks guys. Apologies I thought it was an array. 'name' is a checkbox form so multiple values are sent with the same name. Commented Apr 7, 2013 at 18:05

1 Answer 1

15

There you go: http://jsfiddle.net/mm6Bt/1/

function getURLParam(key,target){
    var values = [];
    if (!target) target = location.href;

    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

    var pattern = key + '=([^&#]+)';
    var o_reg = new RegExp(pattern,'ig');
    while (true){
        var matches = o_reg.exec(target);
        if (matches && matches[1]){
            values.push(matches[1]);
        } else {
            break;
        }
    }

    if (!values.length){
        return null;   
    } else {
        return values.length == 1 ? values[0] : values;
    }
}

var str = 'http://www.example.com?name[]=hello&name[]=world&var1=stam';

console.log(getURLParam('name[]',str));
console.log(getURLParam('var1',str));
Sign up to request clarification or add additional context in comments.

6 Comments

After a lot of struggling, I figured out that we need to append [] to name if it is an array! looks obvious now, but somehow I wasted an hour to notice it.
Also, I replaced 4th line with: "target = decodeURIComponent(location.search);" to get this function to work.
is there a way to return whole query string as object instead of passing params?
I also need this to match empty string, can anyone update it please?
what do you mean ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.