Read query parameters
Parse incoming URL query data and retrieve one or multiple values by name.
JavaScript · Class
URLSearchParams provides utility methods for working with a URL's query string. Its iterable instances preserve ordered name-value pairs and can be modified or serialized.
Create an instance from a query string, iterable pairs, or a record, then use its methods to inspect or modify ordered name-value pairs. Serialization produces a URL-compatible query string, while iteration exposes the pairs in their existing order.
new URLSearchParams()
new URLSearchParams(options)| Name | Type | Description |
|---|---|---|
options | string | iterable<[string, string]> | record<string, string> | A query string, an iterable of string pairs, or a record of string keys and values; the constructor argument is optional. |
A URLSearchParams object instance.
const params = new URLSearchParams("tag=js&tag=web");
params.append("page", "2");
params.set("tag", "javascript");
console.log(params.get("tag"));
console.log(params.getAll("tag"));
console.log(params.toString());Creates parameters from a query string, replaces duplicate tag values, adds a page parameter, reads values, and serializes the result.
Parse incoming URL query data and retrieve one or multiple values by name.
Build links or request URLs while safely encoding names and values.
Manage filters or selections represented by repeated query keys.
URLSearchParams represents URL query data as ordered name-value pairs. It can be constructed from a query string, iterable pairs, or a record, and it provides methods for reading, changing, iterating, and serializing those pairs.
Follow-up: How would you preserve repeated keys? Use append() for each occurrence and getAll() when reading them, rather than set(), which removes other matching values.
get() returns the first value for a name, while getAll() returns every matching value in an array. has() tests whether a name or name-value pair exists.
Follow-up: What happens when a name is absent? get() returns null, getAll() returns an empty array, and has() returns false.
set() assigns a value and removes additional values with the same name; it creates the parameter when none exists. append() always adds another name-value pair.
Follow-up: How is the result encoded? toString() applies application/x-www-form-urlencoded encoding and represents spaces as plus signs.
URLURL.searchURL.searchParamsURLSearchParams.append()URLSearchParams.delete()URLSearchParams.entries()URLSearchParams.get()URLSearchParams.getAll()