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?

Community
  • 1
  • 1
iltdev
  • 1,789
  • 9
  • 27
  • 51
  • 1
    The answer http://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 [] – mplungjan Apr 07 '13 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. – Felix Kling Apr 07 '13 at 17:56
  • 2
    From the question you linked to, you might find this answer helpful: http://stackoverflow.com/a/9362596/218196. – Felix Kling Apr 07 '13 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. – iltdev Apr 07 '13 at 18:05

1 Answers1

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));
neeh
  • 2,777
  • 3
  • 24
  • 32
Adidi
  • 5,097
  • 4
  • 23
  • 30