The Node.js urlSearchParams.get() method is used to access the value of a specific query parameter from a URL. It is a part of the URLSearchParams interface and provides a simple way to work with query strings in a structured manner.
- It retrieves the value associated with a given query parameter name.
- It works with the
URLSearchParamsobject for handling query strings. - It requires the exact parameter name to access its value.
Syntax:
urlSearchParams.get(name)Where
- urlSearchParams : Represents the query string using the
URLSearchParamsobject. - get() : Accesses the value of a specific parameter.
- name : Specifies the query parameter key.
Return value: Returns the parameter value, or null if not found.
Example 1:
// Importing the module 'url'
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 the value for entry 'A'
// by using get() api
const value = params.get('A');
// Display the result
console.log("value for A is " + value);
Output:
value for A is BookExample 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('A', 'Book');
params.append('B', 'Pen');
params.append('C', 'Pencile');
// Getting the value for entry 'A'
// by using get() api
const value = params.get('a');
// Display the result
console.log("value for a is " + value);
Output:
value for a is nullUse cases of urlSearchParams.get() Method
- Extracting specific query parameters from a URL.
- Accessing values passed in HTTP requests.
- Handling user input from query strings.
Reference:Â https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_urlsearchparams_get_name