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¶m=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¶m2=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¶m=bar
would end up being parsed as { param: ["foo", "bar"] }
.