Skip to content

Instantly share code, notes, and snippets.

@tyler-weiss
Created August 23, 2017 01:45
Show Gist options
  • Select an option

  • Save tyler-weiss/979ebca251b762b180ee25be2f8eccdd to your computer and use it in GitHub Desktop.

Select an option

Save tyler-weiss/979ebca251b762b180ee25be2f8eccdd to your computer and use it in GitHub Desktop.
function updateUrlParameter(uri, key, value) {
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment