Skip to content

Instantly share code, notes, and snippets.

@xbotter
Created March 16, 2020 05:58
Show Gist options
  • Save xbotter/3c0707d2adc734784bdf5bbb50180183 to your computer and use it in GitHub Desktop.
Save xbotter/3c0707d2adc734784bdf5bbb50180183 to your computer and use it in GitHub Desktop.
create or update querystring
function paramReplace(uri, key, value) {
// Find the param with regex
// Grab the first character in the returned string (should be ? or &)
// Replace our href string with our new value, passing on the name and delimeter
var re = new RegExp("[\\?&]" + key + "=([^&#]*)");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
var matches = re.exec(uri);
var newUri;
if (matches === null) {
// if there are no params, append the parameter
newUri = uri + separator + key + '=' + value;
} else {
var delimeter = matches[0].charAt(0);
newUri = uri.replace(re, delimeter + key + "=" + value);
}
return newUri;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment