call(back)
Algorithms & Data StructureseasySign in to star problems

URL Query-String Parser

Parse the query string of a URL into an object.

parseQuery("?a=b&c=d")   ->  { a: "b", c: "d" }

Rules

  • A key with no = is a flag: its value is true.
  • A repeated key collects its values into an array, in order.
  • Percent-decode keys and values after splitting on & and =, so %26 inside a value stays a literal &. + decodes to a space.
  • Ignore everything from # on (the fragment) and empty segments (a=1&&b=2&).
  • No ? in the URL → {}. A value that fails to decode is returned as-is rather than throwing.

Hints

Hint 1

Slice from the first ?, cut at #, then split on & and then on the first = per part — decoding only after both splits is what keeps %26 from being treated as a separator.

Hint 2

Wrap decodeURIComponent in a try/catch (malformed input like %E0%A4%A throws) and replace + with a space before decoding.

Hint 3

First value wins the slot; a second occurrence turns the slot into an array; further ones push onto it.

Asked at