URLSearchParams.set & append() in Node

Node.jsServer Side ProgrammingProgramming

Introduction to set()

This function can be used to set the value of the name argument passed with the new value passed. If multiple name-value pair exists, only one name-value pair will be set and all the remaining pairs will be removed as shown in the example below.

Syntax

URLSearchParams.set(name, value);

Parameters

The inputs are name and a value. The name is used to find the value that needs to be updated with the new value given in the argument. New value is not set if the name paramter does not exist in the URL.

Example

// Defining the URL as a constant
const params = new URLSearchParams(
'firstName=John&firstName=Mark&lastName=Chan');

   console.log(params.toString());
   // Setting the name-value pair
   params.set('firstName', 'Jackie');
   // Printing all the params that match value -> 'firstName'
   console.log(params.toString());

Output

firstName=John&firstName=Mark&lastName=Chan
firstName=Jackie&lastName=Chan

Example (When the argument value is not present)

// Defining the URL as a constant
const params = new URLSearchParams(
'firstName=John&firstName=Mark&lastName=Chan');

   console.log(params.toString());
   // Setting the name-value pair
   params.set('midName', 'abc');
   // Printing all the params that match value -> 'firstName'
   console.log(params.toString());

Output

firstName=John&firstName=Mark& lastName=Chan
firstName=John&firstName=Mark&lastName=Chan

Introduction to append()

This function appends a new name-value pair to the existing URL. The name-value pair is appended in the last.

Syntax

URLSearchParams.append(name, value);

Parameters

The name-value pair that needs to appended in the URL.

Example

// Defining the URL as a constant
const params = new URLSearchParams( 'firstName=Jackie');
   // Appending a new name-value pair
   params.append('lastName', 'Chan');
   // Printing the new URL
   console.log(params.toString());

Output

firstName=Jackie&lastName=Chan

Example

// Defining the URL as a constant
const myURL = new URL(
   'https://example.org/?empId=2');

   params.append('empName', 'John');
   // Printing all the params that match value -> 'Id'
   console.log(url);

Output

https://example.org/?empId=2&empName=John
raja
Updated on 28-Apr-2021 07:16:38

Advertisements