Node.js URLSearchParams.sort()

Last Updated : 10 Aug, 2026

The URLSearchParams.sort() method in Node.js is used to sort the key-value pairs in a URL’s query string by their keys. It helps keep query parameters organized in a predictable order.

  • It sorts the parameters based on their keys.
  • It arranges them in ascending order.
  • It updates the original URLSearchParams object.

Syntax:

 urlSearchParams.sort()

Where

  • urlSearchParams: An instance of the URLSearchParams class that stores query parameters.
  • sort(): A method that sorts the parameters by key name.

Return: Sorted order of existing name-value pairs in place by their names. 

Example 1:

javascript
// Create a test URLSearchParams object 
const searchPars = new URLSearchParams("d=4 & c=2 & b=3 & a=1"); 

// Sort the key/value pairs
searchPars.sort();

// Display the sorted query string
console.log(searchPars.toString());

Output:

a=1&b=3&c=2&d=4

Example 2:

javascript
// Create a test URLSearchParams object 
const searchPars = new URLSearchParams(z=4 & a=2 & t=3 & a=1"); 

// Sort the key/value pairs
searchPars.sort();

// Display the sorted query string
console.log(searchPars.toString());

Output:

a=2&a=1&t=3&z=4

Use Cases of URLSearchParams.sort() Method:

  • Organizing query parameters in alphabetical order.
  • Making URL query strings easier to read.
  • Keeping parameter order consistent for comparison or debugging.
Comment

Explore