URL query strings encode structured data in a flat key-value format. Parsing them into objects — and building them back — is a common interview question and everyday utility. This article implements both directions from scratch.
Prerequisites: Data #2 — Flatten & Unflatten Objects
1. Parse Query String → Object
Loading editor...
2. Object → Query String
Loading editor...
3. Parse Nested Query Keys (Bracket Notation)
Some APIs use user[name]=Naveen&user[role]=Engineer for nested data:
Loading editor...
4. Parse URL — Extract Protocol, Host, Path, Query
Loading editor...
5. Full URL Builder
Loading editor...
Key Takeaways
- Always use
encodeURIComponent()/decodeURIComponent()when handling query string values. - Repeated keys are conventionally parsed into arrays.
- Bracket notation (
user[name]) converts to nested objects using path splitting. - For production, use
URLandURLSearchParamsAPIs — these implementations show the internals. - A URL has 6 main parts: protocol, host (hostname + port), pathname, search, hash.
Next: Parsing #3 — Building a Template Engine — replace {{ variables }} and add loops and conditionals.
