Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Parse and build a query string in JavaScript

121 a query string, parsed and rebuilt

fair

Parse a URL query string by hand: strip the leading ?, split on & then on the first =, turn + into a space, decode the percent escapes, and collect a key that appears twice into an array. Then write the builder that goes the other way, dropping undefined, and show that a round trip preserves the meaning even though it does not preserve the string.

Stuck? Three hints, smallest first
  1. 1. Split each pair on = with a rest element, then rejoin the rest — a value is allowed to contain =.
  2. 2. + means a space only in a query string, and decodeURIComponent does not know that, so replace it first.
  3. 3. For the builder, flatMap turns { lga: [a, b] } back into two pairs before anything is encoded.

The answer

const parseQuery = (search) =>
  search
    .replace(/^\?/, '')
    .split('&')
    .filter(Boolean)
    .reduce((acc, pair) => {
      const [rawKey, ...rest] = pair.split('=');
      const decode = (s) => decodeURIComponent(s.replace(/\+/g, ' '));
      const key = decode(rawKey);
      const value = decode(rest.join('='));
      const prior = acc[key];
      const merged = !(key in acc) ? value
        : Array.isArray(prior) ? [...prior, value]
          : [prior, value];
      return { ...acc, [key]: merged };
    }, {});

const buildQuery = (params) =>
  Object.entries(params)
    .flatMap(([key, value]) => (Array.isArray(value) ? value.map((one) => [key, one]) : [[key, value]]))
    .filter(([, value]) => value !== undefined && value !== null)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');

const search = '?state=Lagos&lga=Eti-Osa&lga=Ikeja&q=jollof+rice&price=%E2%82%A65%2C000&flag';
const parsed = parseQuery(search);
const rebuilt = buildQuery(parsed);
const reparsed = parseQuery(rebuilt);

const injected = buildQuery({ q: 'rice&admin=1', page: 2, cursor: undefined, note: null });
const injectedBack = parseQuery(injected);

console.log('parsed  :', parsed);
console.log('rebuilt :', rebuilt);
console.log('injected:', injected);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a plain pair decodes to a string', parsed.state, 'Lagos');
test('a key that appears twice collects into an array, in order', parsed.lga, ['Eti-Osa', 'Ikeja']);
test('plus is a space, but only here', parsed.q, 'jollof rice');
test('percent escapes decode, naira sign and comma included', parsed.price, '₦5,000');
test('a bare key with no equals gets an empty string, not undefined', parsed.flag, '');
test('rebuilding then reparsing gives back the same meaning', reparsed, parsed);
test('but not the same text: a space normalises to %20 and flag gains an =', rebuilt === search, false);
test('encoding is what stops a value forging an extra pair', Object.keys(injectedBack), ['q', 'page']);
test('so the ampersand stays inside the value it came from', injectedBack.q, 'rice&admin=1');

URLSearchParams exists and you should normally use it. Writing this once tells you what it is doing for you: the + rule, the collection of repeated keys, and the encoding that keeps a value from turning into structure. That last one is the security-shaped part — q=rice&admin=1 unencoded is two parameters, and the assertion above proves the builder keeps it as one.

Two small decisions carry weight. Splitting on = with a rest element and rejoining is what allows a base64 value with padding to survive. And a key with no = becoming '' rather than undefined or true is a choice — the platform's own answer is the empty string, which is worth matching so callers behave the same either way.

The round trip is faithful in meaning but not in bytes. + comes back as %20, a bare key gains a trailing =, and key order follows insertion order of the object. Any code comparing query strings as text — a cache key, a signature — has to canonicalise first, or it will treat two identical requests as different.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.