JavaScript replace URL parameter value | Example code

Use searchParams api with set method to replace URL parameter value in JavaScript.

Example code change URL parameter value in JS

HTML example code if 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:

JavaScript replace URL parameter value

Example 2

If Multiple parameter present in URL and update only parameter value.

<!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 yo have any doubts and suggestion 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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.