Skip to content

Instantly share code, notes, and snippets.

@victornpb
Created October 16, 2019 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victornpb/345ae6da6d22f2ff191a4b2444be065a to your computer and use it in GitHub Desktop.
Save victornpb/345ae6da6d22f2ff191a4b2444be065a to your computer and use it in GitHub Desktop.
Simple location.hash parser
/**
* url hash manager
* @author Victor N <victornunes@lett.digital>
*/
const param = (function HashParams() {
function parse(string) {
var params = {};
string.replace(/^[#?]/, '').split('&').forEach(text => {
var p = text.split('=');
var key = decodeURIComponent(p[0]);
var value = decodeURIComponent(p[1]);
if(key) params[key] = value;
});
return params;
}
function serialize(obj) {
var p, arr = [];
for (p in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, p)) continue;
arr.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
return arr.join('&');
}
return {
getAll: function () {
return parse(location.hash);
},
setAll: function (obj) {
location.hash = serialize(obj);
},
set: function (key, val) {
var obj = parse(location.hash);
if (val === undefined) delete obj[key];
else obj[key] = val;
location.hash = serialize(obj);
},
get: function (key) {
return parse(location.hash)[key];
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment