Skip to content

Instantly share code, notes, and snippets.

@rendro
Last active May 4, 2024 15:38
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save rendro/525bbbf85e84fa9042c2 to your computer and use it in GitHub Desktop.
Save rendro/525bbbf85e84fa9042c2 to your computer and use it in GitHub Desktop.
Parse document.cookie into object
document.cookie.split(';').map(function(c) {
return c.trim().split('=').map(decodeURIComponent);
}).reduce(function(a, b) {
try {
a[b[0]] = JSON.parse(b[1]);
} catch (e) {
a[b[0]] = b[1];
}
return a;
}, {});
@12Me21
Copy link

12Me21 commented Aug 29, 2021

so these are neat, but does someone have one that's actually been properly tested?

@lourensdev
Copy link

@12Me21 I actually just ran into an issue using the reduce method. Seems that cookies with long values eventually get cut off, leading to obvious issues when you try do something with that value. I've instead opted to use the Object.fromEntries version with no issues so far

@12Me21
Copy link

12Me21 commented Nov 20, 2021

I've been using this:

function read_cookies() {
	let cookies = {}
	for (let item of document.cookie.split(";")) {
		let match = item.match(/^\s*([^]*?)="?([^]*?)"?\s*$/)
		if (match)
			cookies[match[1]] = decodeURIComponent(match[2])
	}
	return cookies
}

@norwd
Copy link

norwd commented Aug 24, 2022

Rewrite to work on older browsers / js versions:

Object.fromEntries(document.cookie.split(/; */).map(function(c) {
    var index = c.indexOf("=");     // Find the index of the first equal sign
    var key   = c.slice(0, index);  // Everything upto the index is the key
    var value = c.slice(index + 1); // Everything after the index is the value

    // Return the key and value
    return [ decodeURIComponent(key), decodeURIComponent(value) ];
}));

@nkitku
Copy link

nkitku commented Dec 1, 2022

https://stackoverflow.com/a/64472572/8784402

Object.fromEntries(document.cookie.split('; ').map(v=>v.split(/=(.*)/s).map(decodeURIComponent)))

@VillainsRule
Copy link

+1, thanks for the helpful code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment