URLSearchParams.has & delete() in Node


Introduction to has()

This function returns true or false based upon the query argument. The function will return true if name-value pair exists for the argument.

Syntax

var bool = URLSearchParams.has(name);

It will return TRUE if name is present, else FALSE.

Parameters

The input parameter is a name that needs to be searched in the URL.

Example 

// Defining the URL as a constant
const myURL = new URL(
   'https://example.org/?firstName=John');

// Printing whether the argument exists or not
console.log(myURL.searchParams.get('firstName'));

Output

true

Example

// Defining the URL as a constant
const myURL = new URL(
   'https://example.org/?firstName=John');

// Printing whether the argument exists or not
console.log(myURL.searchParams.get('lastName'));

Output

false

Introduction to delete()

It will delete/remove the occurence of the passed argument.

Syntax

URLSearchParams.delete(name);

It will return a modified URL after removing the passed argument.

Parameters

The name is passed that needs to removed from the URL.

Example

// Defining the URL as a constant
const params = new URLSearchParams( 'firstName=John&lastName=Chan');

   console.log(params.toString);
   // Removing the 'firstName' parameter
   params.delete('firstName');
   console.log(params.toString());

Output

firstName=John&lastName=Chan
lastName=Chan

Example  (When arg does not exist)

// Defining the URL as a constant
const params = new URLSearchParams( 'firstName=John&lastName=Chan');

   console.log(params.toString);
   // Removing the 'firstName' parameter
   params.delete('midName');
   console.log(params.toString());

Output

firstName=John&lastName=Chan
firstName=John&lastName=Chan

Updated on: 28-Apr-2021

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements