Use searchParams API with a set method to replace URL parameter value in JavaScript.
Example code change URL parameter value in JS
HTML example code if the parameter is the only parameter.
Example 1
Override parameter value.
var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs
Output:
Example 2
If Multiple parameters are present in the URL and update only the parameter values.
<!DOCTYPE HTML>
<html>
<body>
<script>
let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search);
url.searchParams.set('foo', 'baz');
console.log(url.toString());
</script>
</body>
</html>
Do comment if you have any doubts or suggestions on this JS URL topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version