Practice

Problem 9 of 12

Problem · Medium · 25 min

Read a query string

  • Medium
  • Parsing text
  • Objects

A web address can end with a query string such as color=red&size=m&size=l. It holds pairs of a name and a value. A & separates the pairs. An = separates the name from the value.

Write parseQuery(text). It returns an object.

  • Each name is a key.
  • A name that appears once has a string value. "a=1" gives { a: "1" }.
  • A name that appears more than once has an array of strings, in the order of the text.
  • A pair with no = has the value "".
  • Split each pair at the first =. Later = characters belong to the value.
  • Skip empty pairs. The text "a=1&&b=2" has an empty pair between the two &.
  • Decode every name and every value. A + stands for a space. A % with two hex digits, such as %20 or %C3%A9, stands for a character. Replace each + with a space first, and then use decodeURIComponent.
  • All % codes in the tests are valid.
  • An empty text gives an empty object.

Examples

Call Result
parseQuery('color=red&size=m&size=l') { color: 'red', size: ['m', 'l'] }
parseQuery('q=hello+world') { q: 'hello world' }
parseQuery('') {}

Tasks

2 to do

  1. Task 1, not checked yet. Make parseQuery pass the example tests.

  2. Task 2, not checked yet. Make parseQuery pass the hidden tests.

Task 1 of 2

Make parseQuery pass the example tests.

All tasks

main.js

Ctrl+Enter runs your code. Ctrl+Shift+Enter runs all the tests. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.