URLSearchParams
Reads and builds URL query parameters (the part after ?).
Available since: Web API
Syntax
new URLSearchParams(init)Parameters
| Parameter | Type | Description |
|---|---|---|
| init | string | object | Optional. A string like a=1&b=2, an object or an array of pairs. |
Return value
URLSearchParamsAn object with the get, set, append, has, delete and toString methods.
Examples
Reading parameters:
const params = new URLSearchParams('?city=Berlin&page=2');
console.log(params.get('city'));
console.log(Number(params.get('page')));
console.log(params.get('missing'));Output:
Berlin
2
nullBuilding a query string from an object:
const params = new URLSearchParams({ q: 'tea & cake', limit: 10 });
console.log(params.toString());Output:
q=tea+%26+cake&limit=10Parameters into a plain object:
const params = new URLSearchParams('a=1&b=2');
console.log(Object.fromEntries(params));Output:
{
"a": "1",
"b": "2"
}Notes
Values are always strings — convert numbers yourself. Special characters are encoded automatically, and a space is written as +.
See also
- URL — Parses an address into parts and builds it back.
- encodeURIComponent — Encodes text for safely putting it into part of a URL.
- Object.fromEntries — Creates an object from a list of key–value pairs.
Related recipes
In the tutorial
- Server requests: fetch — The fetch function in JavaScript: GET and POST requests, the response object, status, response.ok, parsing JSON and handling errors.