The urlSearchParams.keys() method in Node.js is part of the URLSearchParams interface and is used to access the keys (parameter names) present in a URLâs query string. It helps in working with query parameters in a clean and structured way.
- It provides access to all parameter keys.
- It includes each key exactly as it appears in the query string.
- It maintains the original order of parameters.
Syntax:
urlSearchParams.keys()Where:
- urlSearchParams: An instance of the
URLSearchParamsclass that holds query parameters. - keys(): A method that retrieves all parameter names as an iterator.
Return value: An iterator object containing all keys in the query string.
Example 1:
// Importing the 'url' module
const http = require('url');
// Creating and initializing
// URLSearchParams object
const params = new URLSearchParams();
// Appending value in the object
params.append('A', 'Book');
params.append('B', 'Pen');
params.append('C', 'Pencile');
// Getting all the name entries only
// by using keys() API
const iterator = params.keys();
// Display result for each name entry
console.log("list of all the keys");
for (const [name] of iterator) {
console.log(name);
}
Output:
list of all the keys
A
B
C
Example 2:
// Importing the module 'url'
const http = require('url');
// Creating and initializing
// URLSearchParams object
const params = new URLSearchParams();
// Appending value in the object
params.append('G', '1');
params.append('F', '2');
params.append('G', '3');
// Getting all the name entries only
// by using keys() api
const iterator = params.keys();
// Display result for each name entry
console.log("list of all the keys");
for (const [name] of iterator) {
console.log(name);
}
Output:
list of all the keys
G
F
G
Use Cases of urlSearchParams.keys() Method
- Iterating through query parameter names.
- Checking for the presence of specific parameters.
- Inspecting or debugging query data.
Reference:Â https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_urlsearchparams_keys