Skip to content

Instantly share code, notes, and snippets.

@0x1211
Created June 9, 2017 06:53
Add or replace a query parameter in Javascript
function addOrReplaceQueryParameter(url, key, value) {
var keyRegExp = new RegExp('([?&])' + key + '=.*?(&|$)', 'i'),
// Checks if there are already some query parameters and set separator
separator = url.indexOf('?') !== -1 ? '&' : '?';
if (url.match(keyRegExp)) {
// $1 and $2 will set separators
return url.replace(keyRegExp, '$1' + key + '=' + value + '$2');
}
return url + separator + key + '=' + value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment