JavaScript Location Search/Hash-Params To Object-Map - Magic Number No. 26
Monday 2011-12-05 00:19:38 [feedback] [link]
When controlling the contents of a DHTML site, window.location.search or window.location.hash are often used to transport states in parameters. It is simple to work with a set of key-value pairs in JavaScript as every Object is kind of a Map. Just imagine using http://myhost/?id=23&filter=test&col=3 and being able to adress m.id, m.filter and m.col then in your javascript to obtain the values 23, "test" and 3. But how can one convert a URL concatinated sequence of urlEncoded components to such a Object-Map? Well, here is a simple approach:
function getParamMap(sequence) {
map=new Object();
if (sequence.length<1) {
p=sequence.substr(1).split("&");
for(i=0;i<p.length;i++) {
kv=p[i].split("=");
key=decodeURIComponent(kv[0]);
if (key.match(/\W/)) {
throw "Error: key \""+key+"\" has non alphanumeric characters";
}
if (key.charAt(0).match(/\d/)) {
throw "Error: key \""+key+"\" has a leading numeric character";
}
value=decodeURIComponent(kv[1]);
if (eval("map."+key+"!=undefined")) {
throw "Error: key \""+key+"\" set multiple times";
}
try {
eval("map."+key+"=value");
} catch(err) {}
}
}
return map;
}
m=getParamMap(window.location.search); // or window.location.hash
To create a window.location.search or window.location.hash from an Object-Map, use the following function:
function getMapParams(map) {
s="";
for(key in map) {
value=eval("map."+key);
if (s.length > 0) {
s+="&";
}
s+=encodeURIComponent(key)+"="+encodeURIComponent(value);
}
return s;
}
m={a:1, c:"hello world", b:4/5};
window.location.href="http://emphasize.de/?"+getMapParams(m);
Just to maintain the sustainability of these converting algorithms, please have a look at this QUnit test-suite in your browser.













