Query String Parse and Stringify
MediumP3Coding
Implement two functions for URL query strings.
parseQuery(query) returns an object:
- A leading
?is ignored. An empty string gives{}. - Pairs are separated by
&and empty pairs are skipped. Each pair is split at the first=; a pair with no=has the value"". - Keys and values are percent-decoded, and
+means a space. - A key that appears once maps to a string. A key that appears several times maps to an array of its values in order.
stringifyQuery(params) returns a query string without a leading ?:
- Pairs are
key=valuejoined by&, in the object's key order; keys and values are encoded withencodeURIComponent. - An array value produces one pair per item (
tag=a&tag=b). - Values are converted with
String;undefinedandnullvalues (and array items) are skipped. - An empty object gives
"".
Both must round-trip simple data: parseQuery(stringifyQuery(x)) equals x when every value is a non-empty string or an array of at least two strings. Input to parseQuery is always validly encoded.
Example 1
- Input
- parseQuery('?a=1&b=x%20y&a=2') stringifyQuery({ q: 'a b', tag: ['x', 'y'] })
- Output
- { a: ['1', '2'], b: 'x y' } 'q=a%20b&tag=x&tag=y'
Constraints
- 0 <= length <= 10^5
- No nested objects.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 14. ⌘Enter runs, ⌘⇧Enter submits.