Parse and Build Query Strings
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write parseQuery(query), which turns a URL query string such as "?q=hello+world&tag=a&tag=b" into an object. A leading "?" is optional. Pairs are separated by "&", and empty pairs are skipped. Each pair splits at its first "=", and a key with no "=" gets the value "". In keys and values, "+" means a space, and percent escapes are decoded with decodeURIComponent, so "%2B" is a real plus. A key that appears once maps to its string; a key that appears more than once maps to an array of its values, in order. Then write buildQuery(params), the reverse, with no leading "?": for each key in order, write key=value with both encoded by encodeURIComponent, joined by "&". Numbers and booleans become their text, an array writes the key once per item, and keys whose value is null or undefined are left out.
Your code must pass
- Parses key and value pairs
- Decodes plus signs and percent escapes
- Collects repeated keys into an array
- Handles keys without values and values with =
- Builds an encoded query string
- Repeats keys for arrays and skips missing values
- Builds and parses back to the same object