Skip to content

Instantly share code, notes, and snippets.

@jeffstephens
Created September 10, 2015 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffstephens/e6d7ca832445550037cf to your computer and use it in GitHub Desktop.
Save jeffstephens/e6d7ca832445550037cf to your computer and use it in GitHub Desktop.
A handy Javascript function to add/update/remove a GET parameter from a URI.
// add or update a GET variable in a URL
function setURIParameter(uri, key, value) {
if (uri.indexOf("&") >= 0) {
console.log("Warning: setURIParameter expects an unencoded URI. This looks like an encoded URI (found &).");
}
// just append the key-value pair to the end of the URI if this parameter isn't present
if (uri.indexOf("?" + key) === -1 && uri.indexOf("&" + key) === -1) {
// support key deletion via a recursive call (so don't add it back)
if (value.length === 0) {
return uri;
}
if (uri.indexOf("?") >= 0) {
return uri + "&" + key + "=" + value;
} else {
return uri + "?" + key + "=" + value;
}
} else {
// remove the parameter then make a recursive call (which will append the value to the end)
var stripped_uri = uri.replace(new RegExp(key + "=[a-zA-Z0-9_-]*&?", "g"), "");
// don't leave garbage ? or & at the end
if (stripped_uri.substr(-1) == "?" || stripped_uri.substr(-1) == "&") {
stripped_uri = stripped_uri.substr(0, stripped_uri.length - 1);
}
return setURIParameter(stripped_uri, key, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment