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
URLSearchParamsobject.
Syntax:
urlSearchParams.sort()Where
- urlSearchParams: An instance of the
URLSearchParamsclass 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:
// 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=4Example 2:
// 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=4Use 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.