The URLSearchParams.toString() method converts the parameters stored in a URLSearchParams object into a properly formatted query string. It organizes all key-value pairs into a string that follows standard URL query formatting.Â
- It formats each parameter as
key=valuein the final string. - It automatically encodes special characters to ensure valid URL formatting.
- It reflects the current state of the
URLSearchParamsobject at the time of calling.
Syntax:Â Â
urlSearchParams.toString()Where
- urlSearchParams : It is an instance of the
URLSearchParamsobject that holds the query parameters. - toString() : It is a method that converts all stored parameters into a single query string.
Return value: It returns a string representing the query parameters in key=value format joined by &.
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('A', 'Pencil');
// Getting string representation
// by using toString() api
const value = params.toString();
// Display the result
console.log("String representation" + " of object : " + value);
Output:
String representation of object : A=Book&B=Pen&A=PencilExample 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('geeks', 'code');
params.append('for', 'eat');
params.append('geeks', 'sleep');
// Getting string representation
// by using toString() api
const value = params.toString();
// Display the result
console.log("String representation" + " of object : " + value);
Output:Â Â
String representation of object : geeks=code&for=eat&geeks=sleepUse Cases of urlSearchParams.toString() Method
- It is used to generate a query string from parameters when constructing URLs dynamically.
- It helps in preparing data to be sent in HTTP requests, such as GET requests.
- It is useful for logging or debugging the current set of query parameters in string form.
- It allows easy reuse of parameters by converting them into a shareable string format.
Reference: https://nodejs.org/dist/latest-v14.x/docs/api/url.html#url_urlsearchparams_tostringÂ