Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get querystring array values in Javascript [duplicate]

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?

like image 748
iltdev Avatar asked Apr 07 '13 17:04

iltdev


1 Answers

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));
like image 156
Adidi Avatar answered Oct 27 '22 18:10

Adidi