JavaScript: Parse a HTTP Cookie header string and return an object of all cookie name-value pairs
JavaScript fundamental (ES6 Syntax): Exercise-171 with Solution
Write a JavaScript program to parse a HTTP Cookie header string and return an object of all cookie name-value pairs.
- Use String.prototype.split(';') to separate key-value pairs from each other.
- Use Array.prototype.map() and String.prototype.split('=') to separate keys from values in each pair.
- Use Array.prototype.reduce() and decodeURIComponent() to create an object with all key-value pairs.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const parseCookie = str =>
str
.split(';')
.map(v => v.split('='))
.reduce((acc, v) => {
acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
return acc;
}, {});
console.log(parseCookie('foo=bar; equation=E%3Dmc%5E2'));
Sample Output:
{"foo":"bar","equation":"E=mc^2"}
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-171-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to create a function that invokes fn with partials prepended to the arguments it receives.
Next: Write a JavaScript program to create a function that invokes the provided function with its arguments transformed.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join