AniUI Academy
medium+250 XPPractice

Parse a cookie header

Cookies arrive as one string, "theme=dark; sid=abc123", whether from document.cookie in the browser or the Cookie header on the server. Every auth helper starts with a parser like this.

Implement parseCookies(header) returning a plain object. Split the string on ; and trim each piece, skipping pieces that are empty. Split each piece on its **first** =; a piece with no = is a flag whose value is the empty string "".

Trim the raw value, and if it both starts and ends with a double quote, strip those two quotes — this happens before any decoding, so token="x y" yields x y. Then decode the key and the value with decodeURIComponent, falling back to the raw text if decoding throws.

When the same name appears twice, the **first** occurrence wins, which is how the browser resolves it. An empty header returns {}.

What it has to do

  • Split on ;, trim each piece, and skip empty pieces.
  • Split each piece on the first =; a piece with no = gets the value "".
  • Strip surrounding double quotes from the raw value before decoding.
  • Decode keys and values with decodeURIComponent, tolerating malformed escapes.
  • Keep the first occurrence when a name is repeated, and return {} for an empty header.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.