String.prototype.split(';') to separate key-value pairs from each other.Array.prototype.map() and String.prototype.split('=') to separate keys from values in each pair.Array.prototype.reduce() and decodeURIComponent() to create an object with all key-value pairs.const parseCookie = str => str .split(';') .map(v => v.split('=')) .reduce((acc, v) => { acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); return acc; }, {});
parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️