Compose query strings
Build or modify request URLs
Node.js · Class
URLSearchParams is a mutable collection for reading and changing URL query parameters. It can be constructed independently or from query data associated with a URL.
URLSearchParams represents URL query data as an ordered collection of string name-value pairs. Construct it from a query string, an object, or key-value pairs, then use its methods to inspect, modify, sort, iterate, or serialize those pairs.
new URLSearchParams();
new URLSearchParams(string);
new URLSearchParams(obj);
new URLSearchParams(iterable);| Name | Type | Description |
|---|---|---|
string | string | An optional query string to parse; a leading question mark is ignored. |
obj | Object | An object representing a collection of key-value pairs. |
iterable | Iterable | An iterable whose elements are key-value pairs. |
name | string | The parameter name to append, set, or retrieve. |
value | string | The string value associated with a parameter name. |
A URLSearchParams instance for the constructors; method return values vary by operation, including strings, null, iterators, or undefined as documented.
const params = new URLSearchParams("?topic=node&tag=api&tag=url");
params.append("format", "json");
params.set("topic", "nodejs");
console.log(params.get("topic"));
console.log(params.getAll("tag"));
console.log(params.toString());Creates parameters from a query string, updates one value, adds another, reads repeated values, and serializes the result.
Build or modify request URLs
Handle filters or tags that may occur more than once
Parse incoming URL query data
URLSearchParams provides read and write access to a URL's query and can also be used independently. It is available as a global class in current Node.js, so importing it is optional.
Follow-up: How would you preserve repeated values? Use append() for each occurrence and getAll(name) when reading, rather than set(), which replaces the value associated with the name.
The string constructor parses a query string into name-value pairs, and an object constructor creates pairs from an object's properties. The object constructor coerces each property key and value to strings.
Follow-up: What happens to a leading question mark in the string input? It is ignored during parsing and does not become part of the first parameter name.
append() adds another name-value pair, while set() assigns a value for a name and replaces existing values for that name. toString() serializes the current parameter collection as a query string.
Follow-up: Why choose URLSearchParams over querystring? URLSearchParams is focused on URL query strings, whereas querystring supports more general delimiter customization.
URLurl.searchParamsurl.searchquerystring