Created
October 16, 2019 19:19
-
-
Save victornpb/345ae6da6d22f2ff191a4b2444be065a to your computer and use it in GitHub Desktop.
Simple location.hash parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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