URLSearchParams sort & toString() in Node


Introduction to sort()

This function sorts the existing name-value pairs by their names. The sorting is done inplace. It used stable algorithm for sorting.

Syntax

URLSearchParams.sort(name);

It will return a sorted order of elements (name-value pairs) by sorting them based on their key value.

Example

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

   // Sorting the parameters
   params.sort();
   console.log(params.toString());

Output

firstName=John&lastName=Chan&midName=abc

Example

// Defining the URL as a constant
const params = new URLSearchParams(
   'z=5&a=2&d=4&c=3&a=1');

   // Sorting the parameters
   params.sort();
   console.log(params.toString());

Output

a=2&a=1&c=3&d=4&z=5

Introduction to toString()

This function converts the urlSearchParameter to string. Characters are encoded when required.

Syntax

URLSearchParams.toString();

It returns the URL after converting it into string. Any unicode character will be encoded.

Example

const params = new URLSearchParams(
'lastName=Chan&midName=abc&firstName=John');

console.log(params.toString());

Output

lastName=Chan&midName=abc&firstName=John

Example

// Defining the URL as a constant
const params = new URLSearchParams(
'z=5&a=2&d=4&c=3&a=1');

   // Printing url params in string type
console.log(params.toString());

Output

z=5&a=2&d=4&c=3&a=1

Updated on: 28-Apr-2021

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements