The URLSearchParams.set() method in Node.js is used to set a new value for a specific key in a URLâs query string. If the key already exists, its value is replaced.
- It sets or updates the value of a parameter.
- It replaces any existing values for the same key.
- It keeps the query string simple and updated.
Syntax:
urlSearchParams.set(name, value)Where,
- urlSearchParams: An instance of the
URLSearchParamsclass that stores query parameters. - set(name, value): A method that assigns a value to the given parameter name.
Return Value: The method does not return any value and returns undefined.
Example 1:
let url = new URL('https://example.com/?fo=4&bar=6');
let params = new URLSearchParams(url.search.slice(1));
//Add another parameter.
params.set('par', 5);
console.log(params.toString());
Output:
fo=4&bar=6&par=5Example 2:
let url = new URL('https://example.com/?a=1&b=2');
let params = new URLSearchParams(url.search.slice(1));
//Add another parameter.
params.set('c', 3);
params.set('d', 4);
console.log(params.toString());
Output:
a=1&b=2&c=3&d=4Use Cases of URLSearchParams.set():
- It is used to update the value of an existing query parameter.
- It is used to remove duplicate values by replacing them with a single value.
- It is used to modify query strings before making requests.