brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: URLSearchParams builds and reads query strings without manual escaping

Javascript
~/tips/tip-javascript-urlsearchparams-query-strings

const params = new URLSearchParams({ q: "fiets reparatie", page: 2 });

Parses and builds URL query strings, with encoding handled for you.

Gluing a query string together with & and encodeURIComponent works until the day you forget one. URLSearchParams does the escaping.

const params = new URLSearchParams({ q: "fiets reparatie", page: 2 });
params.append("tag", "a&b");
params.toString();
// "q=fiets+reparatie&page=2&tag=a%26b"

const url = new URL("https://example.com/search?q=leiden&page=3");
url.searchParams.get("page");   // "3"

get returns the first value or null, getAll returns an array, and has checks for a name. append adds an entry, set replaces the value and drops duplicates, delete removes it. The object is iterable, so a for...of loop gives you the pairs in order.

url.searchParams is a live object. Change it and the URL’s query string changes with it. That makes it the tidy way to add a page number to a link you already have.

The caveat has two parts. First, toString() writes a space as +, following the form encoding rules, which is fine for most servers but not what encodeURIComponent produces. Second, the constructor treats + as a space and does not accept a full URL: pass it url.search, never the whole address. Because of that plus rule, build values with append instead of pasting them into a string, or a plus sign in your data will silently become a space.

Further reading: MDN: URLSearchParams

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link