AniUI Academy
medium+250 XPPractice

Parse a URL query string

Filters, pagination and sort order all live in the query string, and reading it back into state is a job you cannot skip. The awkward parts are keys that appear more than once, keys with no value at all, and the fact that a space can arrive as + or as %20.

Implement parseQuery(search) returning a plain object. Strip one leading ? if present, then split the rest on &, ignoring empty segments so "a=1&&b=2&" is fine.

Split each segment on its **first** = only, so a value may itself contain =. A segment with no = is a flag and its value is the empty string "". Decode both key and value by first replacing every + with a space and then calling decodeURIComponent; if decoding throws on a malformed escape, use the raw text instead.

A key seen once maps to a string. A key seen two or more times maps to an array of all of its values, in order of appearance. Empty or missing input returns {}.

What it has to do

  • Strip an optional leading ? and ignore empty & segments.
  • Split each pair on the first = only; a key with no = gets the value "".
  • Decode + as a space as well as percent escapes, on both keys and values.
  • Collect repeated keys into an array in order of appearance, keeping a single occurrence as a string.
  • Return {} for an empty string.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.