• Node.js Video Tutorials

NodeJS - urlSearchParams.values() Method



The NodeJS urlSearchParams.values() method of class URLSearchParams returns an ES6 iterator that allows iteration through all the values of each name-value pair.

Let’s consider a YouTube URL (‘https://www.youtube.com/watch?z=HY4&z=NJ7), where the portion after the ‘?’ is known as the query segment. In this query, (z) is the name, and (HY4) is the value. Together it forms a name-value pair.

There are two name-value pairs in the query string. So if we assign the query string to the values() method, it returns an ES6 iterator over the values of each name-value pair.

The URLSearchParams API provides methods that give access to read and write the query of a URL. This class is also available on the global object.

Syntax

Following is the syntax of the NodeJS URLSearchParams.values() method

URLSearchParams.values()

Parameters

This method does not accept any parameters.

Return Value

This method returns an ES6 iterator over the values of each name-value pair.

The following examples demonstrate the usage of the NodeJS URLSearchParams.values() method:

Example

If the input URL string contains a query segment, the NodeJS urlSearchParams.values() method returns an iterator over all the values of name-value pairs from the query string.

In the following example, we are trying to get all the values from the name-value pairs of the query string.

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

const MyUrl = new URL('https://www.tutorialspoint.com?1=one&3=three&6=six&9=nine');
console.log("URL: ", MyUrl.href);

const Params = new URLSearchParams('1=one&3=three&6=six&9=nine');
console.log("Query string: " + Params);

console.log('All the values in the query string are: ');
for (const value of Params.values()) {
    console.log(value);
}

Output

As we can see in the below output, the NodeJS values() method returns all the values from the name-value pairs.

 
URL:  https://www.tutorialspoint.com/?1=one&3=three&6=six&9=nine
Query string: 1=one&3=three&6=six&9=nine
All the values in the query string are: 
one
three
six
nine

Example

In the following example, we are appending some name-value pairs to the input query string. Then we are trying to get the values from the name-value pairs.

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

const Params = new URLSearchParams('1=one&3=three&6=six&9=nine');
console.log("Query string: " + Params);

Params.append(12, 'twelve');
Params.append(15, 'fifteen');
console.log('All the values in the query string are: ');

for (const value of Params.values()) {
    console.log(value);
}

Output

On executing the above program, it will generate the following output

Query string: 1=one&3=three&6=six&9=nine
All the values in the query string are: 
one
three
six
nine
twelve
fifteen
nodejs_url_module.htm
Advertisements