Created
July 9, 2015 18:11
-
-
Save joshdcomp/9f53bddc353516552bf4 to your computer and use it in GitHub Desktop.
Reading and removing a get param from a URL
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
/** | |
* 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)); | |
} |
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
/** | |
* 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("&"); | |
} |
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
/** | |
* 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