MillerMedia
MillerMedia

Reputation: 3671

Get Query String Values for Duplicate GET Variables

I've seen how to parse query string info (GET variables) using Javascript and jQuery. There are two different examples here (I've always preferred the second one):

How can I get query string values in JavaScript?

jquery get querystring from URL

The problem is that I have a query string that has two of the same GET variables (they are both called 'search'). When I run the function from the first answer, it only returns the first instance of the 'search' GET variable and the second answer only returns the last 'search' GET variable. An example query string would be:

http://www.example.com?search=this&search=that

I did some searching and there's an answer in this thread that seems to deal with the issue:

https://gist.github.com/kares/956897

But I don't know exactly how to implement it with the way it's written. I basically am looking for a function that can parse the query string and return all (if any) values of that match the particular GET variable (in this case 'search'; in the above example it would return 'this' and 'that').

Thanks for your help!

Upvotes: 1

Views: 2577

Answers (2)

Nouphal.M
Nouphal.M

Reputation: 6344

// Read a page's GET URL variables and return them as an associative array.

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        if(typeof vars[hash[0]]=='undefined'){
         vars.push(hash[0]);
         vars[hash[0]] = [hash[1]];
    }else{
            vars[hash[0]].push(hash[1]);
    }
    }
    return vars;
}

You can find demo here

Upvotes: 0

Rob M.
Rob M.

Reputation: 36511

This should do the trick:

var params = location.search.substr(1).split('&'),
    results = {};

for(var i = 0; i < params.length; i++)
{
    var temp = params[i].split('='),
        key = temp[0],
        val = temp[1];

    results[key] = results[key] || [];
    results[key].push(val);
}

console.log(results); // { search: ["a", "b"] }

Upvotes: 6

Related Questions