Home > Article > Web Front-end > How to add parameters to URL in JavaScript?
In this article, you will learn how to add parameters to a URL in JavaScript. There are two ways to add parameters to the url: the append() method and the set() method.
The append() method is used to specifically add key-value pairs to the url.
set() method adds a value to a specific key. If the key does not exist, a new key is created. If multiple keys exist, update the value of one key and delete the others.
Let’s take a 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)
Step 1 - Define the url with parameters.
Step 2 - Use the append() method to add new parameters to the url.
Step 3 - Display the results.
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)
Step 1 - Define the url with parameters.
Step 2 - Use the append() method to add new parameters to the url.
Step 3 - Display the results.
The above is the detailed content of How to add parameters to URL in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!