JavaScript URLSearchParams set() Tutorial

In this section, we will learn what the set() method is and how to use it in JavaScript.

JavaScript URLSearchParams set () Method

The `set()` method is used to update a given key of a query.

Note: if the target key does not exist in the query, this method will create a new one.

URLSearchParams set() Method Syntax:

URLSearchParams.set(name, value)

URLSearchParams set () Method Parameter:

The method takes two arguments:

  • The first argument is the key which we want to set a new value for it.

Notes:

  1. If there are multiple keys with the same name in the target query, only the first one will be updated and the rest are removed.
  2. If there’s no such key in the target query, the method will create a new one.
  • The second argument is the value of the given key.

URLSearchParams set () Method Return Value:

The method does not return a value.

Example: using URLSearchParams set () method in JavaScript

const searchParams = new URLSearchParams("?name=John&lastName=Doe&address=Mars&name=Omid");

searchParams.set("name","Jack");

console.log(searchParams);

Output:

name=Jack&lastName=Doe&address=Mars

Leave a Reply