Skip to content
RED SAGSkills

Parse a Query String

Parse the query string of url into an object.

First drop the fragment: everything from the first # onwards. If what remains contains no ?, there is no query and the result is {}; otherwise the query is everything after the first ?. Split the query on & and skip empty pieces. Each piece is key=value, split on the first =; a piece with no = has the value "".

In both keys and values, replace every + with a space and then decode percent-escapes with decodeURIComponent. A key that appears once maps to a string; a key that appears more than once maps to an array of all its values in order.

Example 1

Input: url = "https://shop.example/search?q=red+shoes&sort=price%2Casc"
Output: {"q":"red shoes","sort":"price,asc"}
Explanation: `+` becomes a space and `%2C` a comma.

Example 2

Input: url = "/items?tag=new&tag=sale&debug"
Output: {"tag":["new","sale"],"debug":""}
Explanation: `tag` appears twice and `debug` has no value.

Constraints

  • 0 <= url.length <= 10^4
  • All percent-escapes are valid
  • Keys are never __proto__
Hint 1

Use indexOf to find the first ?, # and = rather than split, so values containing = survive.

Hint 2

Turn a string into an array the second time a key shows up.

Good practice for: Backend Developer, Full Stack Developer, Frontend Developer, Mobile App Developer, Automation Test Engineer

Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.