The URLSearchParams.has() method in Node.js is used to check whether a specific parameter exists in a URLâs query string. It provides a simple way to verify the presence of a key without needing to access or process its associated value.
- It takes the parameter name as input and searches for it in the query string.
- It only checks for existence, not the associated data.
- It is used with the
URLSearchParamsinterface for handling URL queries.
Syntax:
urlSearchParams.has(name)Where
- urlSearchParams : Represents the
URLSearchParamsobject that stores and manages query parameters. - name : Refers to the specific query parameter key being checked.
Returns: It returns true if the specified parameter exists, otherwise false.
Example 1:
let url = new URL('https://example.com/?par=5&bar=4');
let param = new URLSearchParams(url.search.slice(1));
param.has('bar') === true;
Output:
trueExample 2:
let url = new URL('https://example.com/?par=5&bar=4');
let param = new URLSearchParams(url.search.slice(1));
param.has('foo') === true;
Output:
falseUse Cases of URLSearchParams.has() Method
- Checking whether a required query parameter is present before processing a request.
- Validating optional parameters to decide conditional logic flow.
- Handling different behaviors based on the existence of specific query keys.
- Ensuring cleaner and safer URL query handling in applications.