How to add a parameter to the URL in JavaScript?


In this article, you will understand how to add a parameter to the URL in JavaScript. There are two methods to add parameters to an url: append() method and set() method.

The append() method is used to specifically add key-value pairs to the url.

The set() method adds the value to a specific key. If the key doesn't exist, a new key is created. If several keys exist, the value is updated for one of them and others are deleted.

Example 1

Let's look at the append() method in this example

let inputUrl = new URL('https://urlExample.com?key1=value1');
let inputParams = new URLSearchParams(inputUrl.search);
console.log("The parameters of the url is defined as: ", inputParams)

inputParams.append('key2', 'value2');

console.log("
The url after adding adding the parameters is: ",inputParams)

Explanation

  • Step 1 − Define an url with parameters.

  • Step 2 − Use the append() method to add new parameters to the url.

  • Step 3 − Display the result.

Example 2

Let's look at the set() method in this example

let inputUrl = new URL('https://urlExample.com?key1=value1');
let inputParams = new URLSearchParams(inputUrl.search);
console.log("The parameters of the url is defined as: ", inputParams)

inputParams.set('key2', 'value2');

console.log("
The url after adding adding the parameters is: ",inputParams)

Explanation

  • Step 1 − Define an url with parameters.

  • Step 2 − Use the append() method to add new parameters to the url.

  • Step 3 − Display the result.

Updated on: 16-Feb-2023

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements