The parseQueryString at http://safalra.com/web-design/javascript/parsing-query-strings/ has some bugs:
- Multiple + are not replaced with space.
- Multiple unescaped equal-sign causes content to be lost.
- Empty input results in an object with key "".
- Multiple empty keys isn't discarded
In the function below the bugs above has been removed and has been tested with FF3, IE7, Opera9 and Chrome1.
function parseQueryString(input){
var out={}, decode=decodeURIComponent, s=input||location.search||"",
kv=("?"===s.charAt(0)?s.slice(1):s).replace(/\+/g," ").split(/[&;]/g),
idx=-1,key,value;
while(++idx<kv.length){
if (kv[idx]==="") continue;
value=kv[idx].split("=");
key=decode(value.shift());
(out[key]||(out[key]=[])).push(decode(value.join("=")));
}
return out;
}
The function above (and the original) expects only the query part of the url: From the question mark to the end of the string or to the first #. If no argument is supplied it will automatically extract the query part from the windows current url.
The result is an object with the keys from the query string, and the value of all keys is an array of all the values.
var data = parseQueryString("?a=test1&a=test2&b=test3");
//Result of data:
{
a:["test1","test2"],
b:["test3]
}
Some examples:
// Alert all values of the a key:
if (data.a && data.a.length) {
for (var i=0;i<data.a.length;++i)
alert(data.a[i]);
}
// Get the first value of a-key:
var value_a = data.a && data.a[0];
// Get the first value of a-key or default:
var value_a = data.a && data.a[0] || "default";