• Node.js Video Tutorials

NodeJS - URLSearchParams.forEach() Method



The NodeJS urlSearchParams.forEach() method of the URLSearchParams class allows the iteration through all the name-value pairs in the query and invokes the given function.

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

Syntax

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

URLSearchParams.forEach(fn[, thisArg])

Parameters

This method accepts two parameters. Those are described below.

  • fn: This parameter holds a function that is used to execute each element. Following are the arguments that can be passed to this function:

    • name: This attribute holds the name of the current entry which is being processed in the URLSearchParams object.

    • value: This attribute holds the value of the current entry which is being processed in the URLSearchParams object.

    • SearchParams: This attribute specifies the URLSearchParams object upon which the forEach() method was called.

    • thisArg: This is the value to use as this when executing the fn.

Return Value

This method returns nothing instead it iterates over each name-value pair in the query string and invokes the specified function.

Example

If we pass a callback function with value and name arguments to the NodeJS urlSearchParams.forEach() method, it iterates over every name-value pair in the query.

The following example demonstrates the usage of the NodeJS urlSearchParams.forEach() method of URLSearchParams class.

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

const MyUrl = new URL('https://www.tutorialspoint.com?3=Three&4=Four&5=Five');
console.log("URL: ", MyUrl.href);
console.log("The name-value pairs: ");

MyUrl.searchParams.forEach(function (value, name) {
    console.log(name, value);
});

Output

As we can see in the output, all the name-value pairs in the query string are iterated.

The name-value pairs: 
3 Three
4 Four
5 Five
nodejs_url_module.htm
Advertisements