Skip to content

JavaScript adds a parameter to URL | Example code

  • by

Use URL.searchParams method with append method to add a parameter to URL in JavaScript. You can also set method.

JavaScript adding a parameter to URL Examples

HTML Example code:

Using append Method

To add a parameter that has multiple values use the append() method.

<!DOCTYPE HTML>
<html>

<body>

	<script>
		var url = new URL("https://www.eyehunts.com");

		url.searchParams.append('param_1', 'val_1');
		console.log(url.toString())

	</script>
</body>
</html>	

Output:

JavaScript adds a parameter to URL

More examples

var url = new URL("http://foo.bar/?x=1&y=2");

// If your expected result is "http://foo.bar/?x=1&y=2&x=42"
url.searchParams.append('x', 42);

// If your expected result is "http://foo.bar/?x=42&y=2"
url.searchParams.set('x', 42);

Using set method

The value of a parameter can be updated with the set() method of URLSearchParams object.

<script>
		var url = new URL("https://www.eyehunts.com");

		url.searchParams.set('param_1', 'val_1');
		console.log(url.toString())

	</script>

Do comment if you have any doubts and 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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading