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%20or%C3%A9, stands for a character. Replace each+with a space first, and then usedecodeURIComponent. - 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
Task 1, not checked yet. Make
parseQuerypass the example tests.Task 2, not checked yet. Make
parseQuerypass the hidden tests.
Task 1 of 2
Make parseQuery pass the example tests.