how to parse an HTTP Cookie header string and return an object of all cookie name-value pairs using javascript?

  Solution: 

Pictorial Represantation:



 Step 1) Use String.split(';') to separate key-value pairs from each other.

Step 2) Use Array.map() and String.split('=') to separate keys from values in each pair.

Step 3) Use Array.reduce() and decodeURIComponent() to create an object with key-value pairs.


Example:

const parseCookie = string =>

  string.split(';').map(item => item.split('=')).reduce((k, i) => {

      k[decodeURIComponent(i[0].trim())] = decodeURIComponent(i[1].trim());

      return k;

    }, {});

testInput: console.log(parseCookie('jshub=great; javascript=js; math=95'));

output: { jshub: 'great', javascript: 'js', math: '95' }



Post a Comment

0 Comments

Close Menu