URLSearchParams.get & getAll() in Node

Node.jsServer Side ProgrammingProgramming

Introduction to get()

This function returns the first name-value pair that is matched with the name passed in the parameter. Returns null if no such value exists. If more than one name-value pair exists it will return the first occurence of that element in the URL.

Syntax

URLSearchParams.get(name);

It will return a single string that matches with the name passed as an argument in the function. If no-pair exists, null is returned.

Example 1

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

// Printing all the params that match value -> 'firstName'
console.log(myURL.searchParams.get('firstName'));

Output

John

Example 2((When the argument value is not present))

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

// Printing all the params that match value -> 'lastName'
console.log(myURL.searchParams.getAll('lastName'));

Output

null

Introduction to getAll()

This function returns all the values that match the given argument. Returns null, if no such pair exists. If more than one name-value pair exist, it will return all the occurencea of that element in an array format.

Syntax

URLSearchParams.getAll(name);

It will return an array of strings with the name-value pairs that matches with the name passed as an argument in the function. If no-pair exists, it will return an empty array.

Example 1

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

// Printing all the params that match value -> 'firstName'
console.log(myURL.searchParams.getAll('firstName'));

Output

['John', 'Mark']

Example 2

// Defining the URL as a constant
const myURL = new URL(
   'https://example.org/?Id=2&Id=3&Id=7');

// Printing all the params that match value -> 'Id'
console.log(myURL.searchParams.getAll('Id'));

Output

['2', '3', '7']

Note –  All modern browsers are supported.

raja
Updated on 28-Apr-2021 07:08:04

Advertisements