A query string is the common way to pass filters, pagination or search keywords through a URL, but hand-built string concatenation goes wrong easily: forgetting to encode special characters, an & splitting a parameter in two, Vietnamese text turning into strange characters. URLSearchParams — built into browsers and Node.js — reads, adds, edits and deletes parameters with a few methods, encoding and decoding correctly by default. Use it whenever you need to read ?page=2 from a URL or build a URL for an API call with filters.
The Problem
Take a product list page at /products?category=ao-thun&sort=price&page=2:
const url = `/api/products?category=${category}&sort=${sort}&page=${page}`;
Three weaknesses: values with spaces or Vietnamese diacritics — for example “áo thun nam” — produce an invalid URL if you forget encodeURIComponent. A value containing & — for example “đồ ăn & uống” — gets cut into a new parameter, making the filter wrong. Reading it back with split(‘&’) then split(‘=’) breaks when a value contains = or an already-encoded character. Forget encodeURIComponent in just one place, and the bug is already silently there.
The Solution
URLSearchParams replaces manual string concatenation. To read parameters, pass window.location.search to the constructor, then use get(), getAll() and has():
const params = new URLSearchParams(window.location.search);
// URL: /products?category=ao-thun&tag=sale&tag=new&page=2
params.get("category"); // "ao-thun"
params.get("page"); // "2" — always a string
params.getAll("tag"); // ["sale", "new"]
params.has("sort"); // false
params.get("missing"); // null
Note: get() only returns the first value, so a repeated parameter like ?tag=sale&tag=new needs getAll(); a missing key returns null; every value is a string.
To build a query string, use set() and append() on an empty object:
const params = new URLSearchParams();
params.set("q", "áo thun nam");
params.set("page", "2");
params.append("tag", "sale");
params.append("tag", "new");
params.toString(); // "q=%C3%A1o+thun+nam&page=2&tag=sale&tag=new"
fetch(`/api/products?${params}`);
set() overwrites the old value of a key, append() adds a new value while keeping the old one. toString() encodes every special character correctly — spaces become +, accented letters become %XX — so it can go straight after the ?.
url.searchParams is linked directly to the URL: set() or delete() updates url.search immediately; combine it with history.pushState() to change pages without reloading:
const url = new URL(window.location.href);
url.searchParams.set("page", "3");
url.searchParams.delete("sort");
history.pushState({}, "", url); // URL changes, the page does not reload
Do not pass a full URL into the constructor — it only takes a query string — and do not interpolate a string containing + into a query, because + becomes a space; values like that must go through append().
Apply It to Your Project
Use URLSearchParams everywhere you build filter links, pagination and API calls with parameters: a search box that syncs its keyword to the URL so a shared link keeps the same results; a page button that only needs set(“page”, …) without losing the filters already selected; when the backend returns an error because of a malformed query, print params.toString() to the console.
Related Posts
JavaScript: Run Multiple Promises at Once with Promise.allSettled — One Failure Won’t Ruin the Batch
JavaScript: Stop API Spam with Debounce — the Search Box Only Calls the API When You Stop Typing
FAQ
Does URLSearchParams work in Node.js?
Yes — it has been a global since Node.js 10, and works exactly like in the browser.
What is the difference between get() and getAll()?
get() returns the first value, or null if the key does not exist. getAll() returns an array of all values; for a repeated parameter like ?tag=sale&tag=new, getAll() is required.
What is the difference between set() and append()?
set() overwrites: it deletes the old value and sets the new one. append() adds a new value while keeping the old one.
Why does a + in a value turn into a space?
Under the application/x-www-form-urlencoded standard, + means a space. To keep a literal +, pass the value through append() or set() so it becomes %2B.
💬 Have you tried this in your own project? If you hit an error or have a shorter way to do it, leave a comment below — I read them all and will add the best ideas to the post.
Sources
MDN Web Docs — URLSearchParams: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
WHATWG URL Standard — URLSearchParams: https://url.spec.whatwg.org/#urlsearchparams
Top comments (0)