Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
function getJsonFromUrl() {
var query = location.search.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
Further enhancements were implemented, see the comments:
- hash based routing (@cmfolio)
- array parameters (@user2368055)
Maybe this should go to codereview SE, but here you go:
function getJsonFromUrl(hashBased) {
var query;
if(hashBased) {
var pos = location.href.indexOf("?");
if(pos==-1) return [];
query = location.href.substr(pos+1);
} else {
query = location.search.substr(1);
}
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
var item = part.split("=");
var key = item[0];
var from = key.indexOf("[");
if(from==-1) result[key] = decodeURIComponent(item[1]);
else {
var to = key.indexOf("]");
var index = key.substring(from+1,to);
key = key.substring(0,from);
if(!result[key]) result[key] = [];
if(!index) result[key].push(item[1]);
else result[key][index] = item[1];
}
});
return result;
}
Note the result[key][index] = item[1]
: a new array field is created, it is enumerable, so it can be iterated by forEach
call. Therefore, you can parse even URLs like
?foo[]=a&foo[x]=b&foo[]=c