The following solution combines other answers and handles some special cases:
- The parameter does not exist in the original url
- The parameter is the only parameter
- The parameter is first or last
- The new parameter value is the same as the old
- The url ends with a
?
character \b
ensures another parameter ending with paramName won’t be matched
Solution:
function replaceUrlParam(url, paramName, paramValue)
{
if (paramValue == null) {
paramValue="";
}
var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
if (url.search(pattern)>=0) {
return url.replace(pattern,'$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/,'');
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}
Known limitations:
- Does not clear a parameter by setting paramValue to null, instead it sets it to empty string. See https://stackoverflow.com/a/25214672 if you want to remove the parameter.