Skip to content

Instantly share code, notes, and snippets.

@kwokhou
Created February 13, 2017 00:52
Show Gist options
  • Save kwokhou/074a5348b8421c024b69aa706d2b2101 to your computer and use it in GitHub Desktop.
Save kwokhou/074a5348b8421c024b69aa706d2b2101 to your computer and use it in GitHub Desktop.
Redirect to URL with query string parameter changed
var updateUrlParameter = function (uri, key, value) {
// remove the hash part before operating on the uri
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (!value) {
// remove key-value pair if value is empty
uri = uri.replace(new RegExp("([?&]?)" + key + "=[^&]*", "i"), '');
if (uri.slice(-1) === '?') {
uri = uri.slice(0, -1);
}
// replace first occurrence of & by ? if no ? is present
if (uri.indexOf('?') === -1) uri = uri.replace(/&/, '?');
} else if (uri.match(re)) {
uri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
uri = uri + separator + key + "=" + value;
}
return uri + hash;
}
window.location.replaceParam = function (param, newValue) {
window.location.replace( updateUrlParameter(window.location.href, param, newValue) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment