Skip to content
GreenSnippets

Parse and build query strings

Convert between query strings and objects with URLSearchParams, including repeated keys.

JavaScript
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

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.