Skip to content

Instantly share code, notes, and snippets.

@ScottKaye
Last active October 8, 2015 14:09
Show Gist options
  • Save ScottKaye/e066638ba1e76642e2c9 to your computer and use it in GitHub Desktop.
Save ScottKaye/e066638ba1e76642e2c9 to your computer and use it in GitHub Desktop.
A library for managing the query string and hash.
(function (url, undefined) {
"use strict";
var _params = {};
var _hash = {};
function buildParams(obj) {
return Object.keys(obj).length ?
"?" + Object.keys(obj).map(function(e) {
return encodeURIComponent(e) + "=" + encodeURIComponent(obj[e]);
}).join("&") : "";
}
function buildHash(obj) {
return Object.keys(obj).length ? "#" + btoa(JSON.stringify(obj)) : "";
}
function updateURL() {
var end = buildParams(_params) + buildHash(_hash);
history.replaceState(null, document.title, window.location.pathname + end);
}
url.getParams = function () {
var query = window.location.search.slice(1);
if (query.length === 0) return [];
query.split("&").forEach(function (q) {
var s = q.split("=");
_params[decodeURIComponent(s[0])] = decodeURIComponent(s[1].replace(/\+/g, " "));
});
return _params;
};
url.removeParam = function (param) {
delete _params[param];
updateURL();
};
url.removeAllParams = function () {
_params = {};
updateURL();
};
url.getParam = function (param) {
return _params[param];
};
url.setParam = function (param, val) {
_params = url.getParams();
if (typeof val === typeof {})
val = JSON.stringify(val);
_params[param] = val;
updateURL();
};
url.getHash = function() {
var hash = window.location.hash.slice(1);
try { return JSON.parse(atob(hash)) } catch (e) {};
return hash.length ? { default: hash } : {};
};
url.getHashParam = function(param) {
return url.getHash()[param];
};
url.setHashParam = function(param, val) {
_hash = url.getHash();
_hash[param] = val;
updateURL();
};
url.removeHashParam = function(param) {
delete _hash[param]
updateURL();
};
url.removeHash = function() {
_hash = {};
updateURL();
};
_params = url.getParams();
_hash = url.getHash();
}(window.url = window.url || {}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment