• Node.js Video Tutorials

NodeJS - urlSearchParams.has() Method



The NodeJS urlSearchParams.has() method of URLSearchParams class prints true if the name passed to this method is present, else it prints false.

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

Let’s look into an example to understand the has() method in a better way. Consider a ‘Search Engine’ in NETFLIX and we are trying to search for a particular movie in it. If it is present, it will show you that particular movie, else it displays an error message.

Syntax

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

URLSearchParams.has(name)

Parameters

  • name: This specifies the name of the parameter to find.

Return Value

This method returns a Boolean value.

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

Example

If the name passed to the NodeJS urlSearchParams.has() method is present in the query string, it returns true.

In the following example, we are trying to check if the name ‘header’ is present in the query string.

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

const MyUrl = new URL('https://www.tutorialspoint.com?title=1&header=2&body=3&footer=4');
console.log("URL: ", MyUrl.href);

const Params = new URLSearchParams('title=1&header=2&body=3&footer=4');
console.log("Query string: " + Params);

console.log("The name 'header' is present in query: " + Params.has("header"));

Output

As we can see in the output, the NodeJS has() method returned true because the name ‘header’ is in the query string.

URL:  https://www.tutorialspoint.com/?title=1&header=2&body=3&footer=4
Query string: title=1&header=2&body=3&footer=4
The name 'header' is present in query: true

Example

If the name passed to the has() method is not present in the query string, it returns false.

In the following example below, we are trying to find whether the name "header" is in the query string.

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

const MyUrl = new URL('https://www.tutorialspoint.com?title=1&header=2&body=3&footer=4');
console.log("URL: ", MyUrl.href);

const Params = new URLSearchParams('title=1&header=2&body=3&footer=4');
console.log("Query string: " + Params);

console.log("The name 'contactUS' is present in query: " + Params.has("ContactUS"));

Output

After executing the above program, the has() method returns false because the name which has been searched is not present in the query string.

URL:  https://www.tutorialspoint.com/?title=1&header=2&body=3&footer=4
Query string: title=1&header=2&body=3&footer=4
The name 'contactUS' is present in query: false
nodejs_url_module.htm
Advertisements