The JavaScript URLSearchParams object
The URLSearchParams object reads and builds URL query strings (the part after ?) without manual parsing. const params = new URLSearchParams(location.search); params.get("page") reads a parameter. Use set(), append() and toString() to build one. It handles encoding for you.
Overview
URLSearchParams takes the pain out of working with query strings — the ?page=2&sort=name part of a URL. Instead of splitting and decoding strings by hand, you get a clean object with methods. Create one from a query string (or from location.search to read the current page's params), and read values with get(name).
The read methods cover the common cases: get(name) returns the first value (or null), getAll(name) returns every value for a repeated key, and has(name) checks existence. For building or editing, set(name, value) replaces, append(name, value) adds, delete(name) removes, and toString() serializes back to a properly encoded query string — special characters are escaped automatically, which is easy to get wrong by hand.
It's iterable, so you can loop it with for...of to get [key, value] pairs, or convert the whole thing to an object with Object.fromEntries(params). It's also part of the URL object — new URL(href).searchParams — which is handy when parsing full URLs. For sending form fields as a URL-encoded request body, you can even pass a URLSearchParams straight to fetch().
Syntax
const params = new URLSearchParams(location.search);
params.get("page"); // "2" (or null)
params.getAll("tag"); // all values for repeated key
params.has("sort"); // true / false
const out = new URLSearchParams();
out.set("q", "hello world");
out.toString(); // "q=hello+world" (encoded)
Example
<pre id="out" style="font:14px ui-monospace,monospace"></pre>
<script>
const params = new URLSearchParams('?page=2&sort=name&tag=js&tag=css');
document.getElementById('out').textContent =
'page: ' + params.get('page') + '\n' +
'tags: ' + params.getAll('tag').join(', ') + '\n' +
'as object: ' + JSON.stringify(Object.fromEntries(params));
</script>
Best practices
- Read the current page's query with
new URLSearchParams(location.search). - Use
getAll()for parameters that can repeat;get()returns only the first. - Build query strings with
set()/append()andtoString()— it encodes for you. - Convert all params to an object with
Object.fromEntries(params).
Frequently asked questions
How do I get a query parameter in JavaScript?
new URLSearchParams(location.search).get("name"), which returns the value or null.How do I build a query string?
URLSearchParams, use set()/append(), then toString() — it encodes special characters automatically.How do I read repeated parameters?
getAll("name"), which returns an array of all values for that key.How do I convert query params to an object?
Object.fromEntries(new URLSearchParams(location.search)).