Skip to content

Instantly share code, notes, and snippets.

@cocoabox
Last active August 29, 2015 14:12
Show Gist options
  • Save cocoabox/136cd2555065463bbc7a to your computer and use it in GitHub Desktop.
Save cocoabox/136cd2555065463bbc7a to your computer and use it in GitHub Desktop.
converts fragment #aa=bb&cc=dd+ee into dictionary {"aa":"bb", "cc" : "dd ee"}
/**
* input: #hogehogehogehoge output: "hogehogehogehoge"
* input: #one/two/three output: "one/two/three"
* input: #a=1&b=2&c=hello+me output: {a:1, b:2, c:"hello me"}
* input: #a&b=2&c=hello?+me output: {a:true, b:2, c:"hello? me"}
* input: #a&b=2=3=4=5 output: {a:true, b:[2,3,4,5]}
*
* @return {string|object}
*/
function fragment_decode() {
var fragment_dict = {};
var fragment_list = typeof window.location.hash === "string" && window.location.hash
? window.location.hash.replace(/^#!?/,"").split("&")
: []
;
if (fragment_list.length == 1) {
return fragment_list[0];
}
for (var i = 0; i < fragment_list.length; ++i) {
var frag = fragment_list[i].split("=");
for (var j = 0; j < frag.length; ++j) {
frag[j] = decodeURIComponent((frag[j] + '').replace(/\+/g, '%20'));
}
if (frag.length == 1) {
fragment_dict[frag[0]] = true;
}
else if (frag.length == 2) {
fragment_dict[frag[0]] = frag[1];
}
else if (frag.length > 2) {
fragment_dict[frag[0]] = [];
for (var j = 1; j < frag.count; ++j) {
fragment_dict[frag[0]].push(frag[j]);
}
}
}
return fragment_dict;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment