SnippetJavaScript
Read URL query parameters
Wraps URLSearchParams to read single values, all values of a repeated key, and every param as a plain object, from a full URL string.
Last updated
Snippetjavascript
function getQueryParams(url) {
const params = new URLSearchParams(new URL(url).search);
return {
get: (key) => params.get(key),
getAll: (key) => params.getAll(key),
entries: () => Object.fromEntries(params),
};
}
// const q = getQueryParams("https://x.test?tag=js&tag=css&page=2");
// q.getAll("tag") -> ["js", "css"]How it works
new URL(url).search extracts just the query string (including its leading "?"), which URLSearchParams then parses into an iterable, decoded key/value structure — no manual splitting on "&" and "=", and percent-encoded characters are decoded for you automatically.
The wrapper exposes get, getAll and entries separately because they answer different questions: get() returns only the FIRST value for a key, which silently drops data when a key repeats (as multi-select filters or checkboxes often produce) — getAll() is what you want whenever a key might appear more than once.
Edge cases to know
- →Object.fromEntries(params) keeps only the last value for any repeated key, since a plain object can't hold two values under one key — use getAll for those, not entries.
- →This needs a full, absolute URL string because it goes through the URL constructor; in a browser, pass location.href for the current page's params instead of a relative path.
- →All values come back as strings — "page=2" gives you the string "2", not the number 2, so cast before doing arithmetic on it.