The URLSearchParams.getAll() method in Node.js is used to get all values associated with a specific key in a URL’s query string. It is helpful when the same parameter appears more than once.
- It is useful for repeated query parameters.
- It keeps the values in the same order as they appear.
Syntax:
urlSearchParams.getAll(name)Where
- urlSearchParams: An instance of the
URLSearchParamsclass that stores query parameters. - getAll(name): A method that returns all values linked to the given parameter name.
Return Value: An array containing all values for the specified key. If the key is not found, it returns an empty array.
Example 1:
let url = new URL('https://example.com/?par=5&bar=2');
let params = new URLSearchParams(url.search.slice(1));
//Add a second par parameter.
params.append('par', 4);
console.log(params.getAll('par'))'
Output:
['5', '4']Example 2:
let url = new URL('https://example.com/?par=5&bar=2&bar=7&par=4&bar=9');
let params = new URLSearchParams(url.search.slice(1));
console.log(params.getAll('bar'));
Output:
['2','7','9']Use Cases of Node.js URLSearchParams.getAll():
- Retrieving multiple values for the same query parameter.
- Handling URLs with repeated keys.
- Reading all submitted values from form-style query strings.