Parse and build query strings
Convert between query strings and objects with URLSearchParams, including repeated keys.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function parseQuery(search) {
const out = {};
for (const [key, value] of new URLSearchParams(search)) {
if (key in out) out[key] = [].concat(out[key], value);
else out[key] = value;
}
return out;
}
function buildQuery(params) {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null) continue;
for (const v of [].concat(value)) search.append(key, String(v));
}
return search.toString();
}Example / expected output
parseQuery("?q=js&tag=a&tag=b") // { q: "js", tag: ["a", "b"] }
buildQuery({ q: "a b", page: 2 }) // "q=a+b&page=2"How it works
URLSearchParams handles encoding and decoding for you. Object.fromEntries would drop repeated keys (?tag=a&tag=b), so this helper collects repeats into arrays. Values are always strings; convert numbers yourself.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Truncate a string with an ellipsis
Shorten text to a maximum length without cutting in the middle of a word or a Unicode character.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- JavaScript Tested
Slugify a string for URLs
Convert any title into a lowercase, hyphenated, accent-free slug that is safe to use in a URL.

