Convert cookie to object
Parse a Cookie header string into name–value pairs.
function parseCookies(cookie) { return Object.fromEntries(cookie.split(';').filter(item => item.includes('=')).map(item => [item.slice(0, item.indexOf('=')).trim(), item.slice(item.indexOf('=') + 1).trim()])); }
Input & expected output
Input
"theme=dark; session=abc=def; lang=pt-BR"Expected output
{
"theme": "dark",
"session": "abc=def",
"lang": "pt-BR"
}The edge case
Input
""Expected output
{}Know the limits
- The original read document.cookie and split on every =, which cut values such as "abc=def"; this version parses any header string and splits on the first = only.
- Values are not URI-decoded; apply decodeURIComponent where your app encodes them.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Convert cookie to object from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Parses any Cookie header string instead of document.cookie and splits on the first = only; the original cut values containing =. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Convert Celsius to Fahrenheit — Apply the temperature conversion without rounding the result.
- Convert hex to RGB — Expand #rgb if needed and read the red, green and blue channels.
- Convert URL parameters to object — Read a query string into an object; repeated keys become arrays.