• Node.js Video Tutorials

NodeJS - new URLSearchParams(obj)



The new URLSearchParams(obj) class constructor will create a query string object with a JSON object.

The URLSearchParams class is a global type that is used to deal only with URL query strings.

A new query string object can be constructed by using the below URLSearchParams class constructor.

Syntax

Following is the syntax of the NodeJS new URLSearchParams(obj) class constructor

new URLSearchParams(obj)

Parameters

  • obj: This parameter holds an object representing a collection of key-value pairs.

Return Value

This class constructor creates a query string with a JSON object.

Example

In the following example, we are trying to create a query string object with a JSON object that contains a collection of key-value pairs.

const url = require('node:url');

const params = new URLSearchParams({
    user: ["Sharukh", "Hrithik"],
    query: ['HTML', 'CSS', 'JavaScript']
});
console.log(params.toString());

Output

As we can see in the output below, the toString() method returned the query string object’s key-value pairs as a string.

user=Sharukh%2CHrithik&query=HTML%2CCSS%2CJavaScript

Example

In the following example, we are trying to get the values of the keys using params.getAll() method.

const url = require('node:url');

const params = new URLSearchParams({
    user: ["Sharukh", "Hrithik"],
    query: ['HTML', 'CSS', 'JavaScript']
});
console.log(params.getAll('user'));
console.log(params.getAll('query'));

Output

As we can see in the output, the params.getAll() method returned the key’s values.

[ 'Sharukh,Hrithik' ]
[ 'HTML,CSS,JavaScript' ]
nodejs_url_module.htm
Advertisements