Skip to content
UniCircle
MediumCodingHTTP and URLs

Parse a URL query string

Question NODE-COD-001

Parse a URL query string into an object, the way a web framework fills req.query.

Rules:

  • An optional leading ? is ignored. Pairs are separated by &; empty segments are skipped.
  • In each segment, the text before the first = is the key and the rest is the value. A segment with no = has the value "".
  • Decode keys and values: + means a space, and %XX escapes are UTF-8 bytes (decode as decodeURIComponent does).
  • 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.
  • Keys appear in the output in the order they are first seen.

Constraints

  • The line is at most 5000 characters and is correctly encoded.
  • Decoded keys are non-empty and made of letters only.

Input and output

Input
One line: the query string.
Output
One line: the result as compact JSON.

Examples

Input 1

?course=btech&branch=cse&branch=ece&city=New+Delhi

Output

{"course":"btech","branch":["cse","ece"],"city":"New Delhi"}

Repeated keys become arrays; + means a space.

Input 2

q=fees%20%26%20placements&page=2&debug

Output

{"q":"fees & placements","page":"2","debug":""}

%20 is a space and %26 is &; a key without = gets an empty value.

Show hints
  • Replace + with a space before percent-decoding, not after (an encoded %2B must stay a plus).
  • Split each segment on the first = only.
Show the explanation

Split on &, skip empty pieces, and split each piece at the first = (indexOf + slice, not split('='), because values may contain encoded or literal =).

Decode in the right order: turn + into spaces first, then decodeURIComponent. Doing it the other way would turn an encoded plus (%2B) into a space.

When a key repeats, convert the stored string into an array on the second occurrence and push after that. Use an object without a prototype (Object.create(null)) or a Map, so keys such as constructor cannot clash with inherited properties — a real security concern known as prototype pollution.

Node's built-in URLSearchParams does the parsing (new URLSearchParams(s).getAll(key)); interviewers ask for a hand-written version to test string handling.

Original UniCircle question. Last reviewed 22 Oct 2026.