Skip to content

Instantly share code, notes, and snippets.

@joshdcomp
Created July 9, 2015 18:11
Show Gist options
  • Save joshdcomp/9f53bddc353516552bf4 to your computer and use it in GitHub Desktop.
Save joshdcomp/9f53bddc353516552bf4 to your computer and use it in GitHub Desktop.
Reading and removing a get param from a URL
/**
* Clear a specific get param from a url and replace it in window history
*/
function clearParam(param) {
// Get the querystring as a hash
var params = window.queryParams();
// Remove the param
delete params[param];
// Quickest way to remove the whole querystring, which is fine because we're rebuidling it anyway
var href = window.location.href.split("?")[0];
// Don't save the original get param to history
window.history.replaceState(null, null, href + serialize(queryParams));
}
/**
* Given a hash (even a multi-level hash), return a http querystring
*/
serialize = function(obj, prefix) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push(typeof v == "object" ? serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
/**
* Takes the query params of the url or a passed querystring and returns a hash
*/
window.queryParams = function(str) {
return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n=n.split("="),this[n[0]]=n[1],this;}.bind({}))[0];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment