Skip to content

Instantly share code, notes, and snippets.

@JenkinsDev
Last active August 29, 2015 14:16
Show Gist options
  • Save JenkinsDev/745fbd548c58eb64b85f to your computer and use it in GitHub Desktop.
Save JenkinsDev/745fbd548c58eb64b85f to your computer and use it in GitHub Desktop.
JavaScript update GET query key/value pair and redirect.
function redirectWithGetDataChange(key, value) {
var getData = window.location.search.substr(1).split("&"),
getKeyValue = null,
getKeyChanged = false;
for (var i=0; i<getData.length; i++) {
getKeyValue = getData[i].split("=");
if (getKeyValue[0] == key) {
getData[i] = key + "=" + value;
getKeyChanged = true;
}
}
// If the get "key" hasn't been changed then we will take that as a sign
// showing that the get key doesn't exist in the current URL so we add
// it ourselves.
if (! getKeyChanged) {
getData.push(key + "=" + value);
}
window.location.href = window.location.pathname + "?" + getData.join("&");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment