0

I'm using the code below to get query parameters for a search in javascript. Is there any particular reason why this wouldn't be able to handle multiple parameters? I seem to be having trouble implementing it.

var params = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
    q = q.split('&');
    for(var i = 0; i < q.length; i++){
        hash = q[i].split('=');
        params.push(hash[1]);
        params[hash[0]] = hash[1];
    }
}

2 Answers2

1

You could potentially use a regex to get the params.

var test = 'example.com/index.html?param1=foo&param2=data#icouldhaveahashtoo';
var params = {};

test.replace(/[?&]([^=]+)[=]([^&#]+)/g, function(match, key, value){
  params[key] = value;
  return '';
});

console.log(params);
Taplar
  • 24,788
  • 4
  • 22
  • 35
-1

Seems your code works fine, however, it won't work properly with URL's with query parameters assigned more than one value (like http://example.com/page.php?param=foo&param=bar). Additionally, if one of the query string parameter names is length or something, that could do bad things to the params array - might be better to try a different container.

var params = [], hash;
var q = 'example.com/index.html?param1=foo&param2=data'.split('?')[1];
if(q != undefined){
    q = q.split('&');
    for(var i = 0; i < q.length; i++){
        hash = q[i].split('=');
        params.push(hash[1]);
        params[hash[0]] = hash[1];
    }
}

console.dir(params); // Array[2] 0: "foo" 1: "data" length: 2 param1: "foo" param2: "data" __proto__: Array[0]

I'd suggest having the params variable be an object, and skip the line params.push(hash[1]), because you can iterate over the properties using a for..in loop easily enough, and the order of the parameters shouldn't matter anyways. If there's more than one value for a parameter of a particular name, then the value of that parameter would be an array. For example, ?param=foo&param=bar would end up being parsed as { param: ["foo", "bar"] }.

Hatchet
  • 5,320
  • 1
  • 30
  • 42