Skip to content

Instantly share code, notes, and snippets.

@santarinto
Created June 15, 2016 13:47
Show Gist options
  • Save santarinto/40a87ca288acf79d7d0b5d53459571b7 to your computer and use it in GitHub Desktop.
Save santarinto/40a87ca288acf79d7d0b5d53459571b7 to your computer and use it in GitHub Desktop.
function to parse hash
function hashParse(url) {
function assign(obj, prop, value) {
prop = prop.split(".");
if (prop.length > 1) {
var e = prop.shift();
assign(obj[e] = Object.prototype.toString.call(obj[e]) === "[object Object]" ? obj[e] : {},
prop,
value);
} else
obj[prop[0]] = value;
}
url = url || window.location.href;
var hash = url.indexOf('#') == -1 ? '' : url.substr(url.indexOf('#') + 1);
if (hash.length == 0) {
return {};
}
hash = hash.split('&').filter(function (p) {return p.length > 0;});
if (hash.length == 0) {
return {};
}
var parsed = {};
hash.forEach(function (item) {
var name = item, value = null;
if (item.indexOf('=') != -1) {
name = item.substr(0, item.indexOf('='));
value = item.substr(item.indexOf('=') + 1);
}
name = name.split('][').join('.').replace('[', '.').replace(']', '');
assign(parsed, name, value);
});
return parsed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment