Introduction to URLSearchParams API in Node.js

Node.jsServer Side ProgrammingProgramming

Node is an open source project that is used to create dynamic web applications. The URLSearchParams API is an interface. It defines different utility that is required to work with the query string of the URL.

In this article, we will discuss the four different constructors of URLSearchParams that can be used as per the requirement.

new URLSearchParams()

This is a no argument constructor and therefore only used to initialize a new Empty URLSearchParams() object.

Syntax

var params = new URLSearchParams();

new URLSearchParams(string)

This constructor can accept a string as an input parameter along with instantiating a new URLSearchParams object.

Syntax

const params = new URLSearchParams('firstName=pqr & lastName=xyz');
   console.log(params.get('firstName'));
   console.log(params.get('lastName'));

Output

pqr
xyz

new URLSearchParams(object)

This contructor accepts an object as an input parameter with a collection of key-value pairs to initialize a new URL. The key-value pair are always converted to string type. Duplicate keys are not allowed.

Syntax

const params = new URLSearchParams({
   user: 'John',
   subjects: ['Physics', 'Chemistry', 'Maths']
});
console.log(params.toString());

Output

user=John&subjects=Physics%2CChemistry%2CMaths

new URLSearchParams(iterable)

This contructor accepts an iterable object that contains a collection of key-value pairs to initialize a new URLSearchParams object. Since URLSearchParams is itself an iterable an object, therefore we can have another iterable URLSearchParams inside new URLSearchParams(). Duplicate keys are allowed inside this.

Syntax

const map = new Map();
   map.set('Taj Mahal', 'Agra');
   map.set('Qutub Minar', 'Delhi');
   map.set('Gateway of India', 'Mumbai');
   params = new URLSearchParams(map);
   console.log(params.toString());

Output

Taj+Mahal=Agra&Qutub+Minar=Delhi&Gateway+of+India=Mumbai
raja
Published on 27-Apr-2021 11:23:39
Advertisements