Skip to the code
cf.
+25 XP

#627 Read a Query String

medium

A product listing page keeps its filters in the URL, like ?color=red&size=m&size=l&q=summer+dress. Write parseQuery(query) that turns such a string into an object.

  • A leading ? is ignored. Pairs are separated by &, and empty pairs are skipped.
  • Each pair is split at its first =. A pair without = has the value "". Pairs with an empty key are skipped.
  • In keys and values, + means a space, and %XX escapes are decoded (use decodeURIComponent after replacing +).
  • A key that appears once maps to its string value. A key that appears more than once maps to an array of all its values in order.

Example 1

Input: query = "?color=red&size=m&size=l&q=summer+dress"
Output: {"color":"red","size":["m","l"],"q":"summer dress"}

size appears twice, so it becomes an array; + becomes a space.

Example 2

Input: query = "sort&page=2"
Output: {"sort":"","page":"2"}

sort has no =, so its value is empty.

Constraints

  • 0 <= query.length <= 10^4
  • All % escapes in the input are valid.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).