w3resource

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:

JavaScript Fundamental: Parse a HTTP Cookie header string and return an object of all cookie name-value pairs.

Flowchart:

flowchart: Parse a HTTP Cookie header string and return an object of all cookie name-value pairs

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.



JavaScript: Tips of the Day

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

includes doesn't have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);

Ref: https://bit.ly/3fFFgZv