URLSearchParams: Read and Update URL Query Parameters in JavaScript
Contents
- Read a parameter from the current URL
- The methods
- get(), getAll() and has()
- set(), append() and delete()
- Loop over all parameters
- Creating URLSearchParams
- From a string, an object or a form
- Use it through the URL object
- Practical examples
- Build a fetch request
- Update the URL without reloading
- Remove tracking parameters
- Common gotchas
- FAQ
URLSearchParams is a built-in JavaScript API for working with the query string of a URL: the part after the ?, like ?q=css&page=2. It parses it for you, handles encoding, and turns it back into a string, so you never have to split on & and = by hand.
Read a parameter from the current URL
The most common use. For https://example.com/search?q=css+grid&page=2:
const params = new URLSearchParams(window.location.search);
params.get('q'); // "css grid" (+ is decoded as a space)
params.get('page'); // "2" (always a string)
params.get('sort'); // null (missing)
params.has('page'); // true
The methods
get(), getAll() and has()
get() returns the first value or null. A key can appear more than once (?tag=css&tag=html); getAll() returns all of them as an array.
const params = new URLSearchParams('?tag=css&tag=html&page=2');
params.get('tag'); // "css"
params.getAll('tag'); // ["css", "html"]
params.has('page'); // true
params.size; // 3 entries
set(), append() and delete()
set() replaces all values for a key; append() adds another one. toString() gives you the encoded query string, without the leading ?. delete is one of the JavaScript reserved keywords, but it is fine as a method name like this.
const params = new URLSearchParams();
params.set('q', 'flex & grid');
params.append('tag', 'css');
params.append('tag', 'layout');
params.set('page', 1); // numbers are converted to strings
params.delete('page');
params.toString(); // "q=flex+%26+grid&tag=css&tag=layout"
Loop over all parameters
URLSearchParams is iterable. Each entry is a [key, value] pair, and Object.fromEntries() turns it into a plain object (keeping only the last value of repeated keys).
const params = new URLSearchParams('?q=css&page=2');
for (const [key, value] of params) {
console.log(key, value);
}
const obj = Object.fromEntries(params); // { q: "css", page: "2" }
Creating URLSearchParams
From a string, an object or a form
The constructor accepts a query string (with or without ?), an object, an array of pairs, or FormData.
new URLSearchParams('?q=css&page=2');
new URLSearchParams({ q: 'css', page: 2 });
new URLSearchParams([['tag', 'css'], ['tag', 'html']]);
new URLSearchParams(new FormData(document.querySelector('form')));
Use it through the URL object
For a full URL, create a URL and use its searchParams property. Changes to it update the URL automatically, so this is the cleanest way to build links.
const url = new URL('https://api.example.com/posts');
url.searchParams.set('category', 'css');
url.searchParams.set('per_page', 10);
url.href; // "https://api.example.com/posts?category=css&per_page=10"
Practical examples
Build a fetch request
Never glue user input into a URL with template strings: a & or # in the input breaks the request. URLSearchParams encodes it properly. The same goes for search queries to the WordPress REST API.
const query = 'c# & .net';
// Broken: & and # aren't encoded
fetch(`/api/search?q=${query}`);
// Correct
const params = new URLSearchParams({ q: query, limit: 20 });
const res = await fetch(`/api/search?${params}`);
Update the URL without reloading
Keep filters, tabs or search terms in the URL so the page can be bookmarked and shared. history.replaceState changes the address bar without a reload; use pushState instead if the Back button should undo the change.
function setFilter(key, value) {
const url = new URL(location.href);
if (value) url.searchParams.set(key, value);
else url.searchParams.delete(key);
history.replaceState(null, '', url);
}
setFilter('category', 'css'); // ?category=css
setFilter('category', ''); // removed
Remove tracking parameters
Strip utm_* parameters from the address bar after your analytics has read them, so people share clean links.
const url = new URL(location.href);
for (const key of [...url.searchParams.keys()]) {
if (key.startsWith('utm_')) url.searchParams.delete(key);
}
history.replaceState(null, '', url);
Common gotchas
- Every value is a string.
params.get('page')returns"2", not2. Convert withNumber(). Booleans too:"false"is a truthy string. Here’s every way to convert a string to a number in JavaScript, and where each one trips you up. - Missing keys return
null. Use a default:Number(params.get('page') ?? 1). +means space. In query strings,+is decoded as a space, so a raw+in a value must be sent as%2B.URLSearchParamsdoes this right when you useset(), but not if you build the string yourself.- It’s not the hash.
location.searchexcludes the#part. For#/page?x=1style URLs, parselocation.hashinstead. - Arrays have no special syntax. Some back ends use
tags[]=a&tags[]=b; toURLSearchParams,tags[]is just a key name.
FAQ
How do I get a query parameter from the URL in JavaScript?
new URLSearchParams(location.search).get('name'). It returns the value as a string, or null if the parameter isn’t there.
How do I convert URLSearchParams to an object?
Object.fromEntries(params). Repeated keys keep only their last value; use getAll() for those.
Does URLSearchParams encode values?
Yes. set() and append() take raw values, and toString() returns them percent-encoded (with spaces as +).
Does URLSearchParams work in Node.js?
Yes. URL and URLSearchParams are global in Node.js, Deno and Bun, so the same code runs on the server.