Skip to content

Instantly share code, notes, and snippets.

@vercte
Last active May 25, 2022 02:40
Show Gist options
  • Save vercte/4335468d212729daf8deaa35cbcf709a to your computer and use it in GitHub Desktop.
Save vercte/4335468d212729daf8deaa35cbcf709a to your computer and use it in GitHub Desktop.
Adventures in RegEx: Cookie parser (EMCAScript flavor)

Parses a document's cookie Use:

let cookie = parseCookie(document.cookie)
if(cookie.theme) {
  setTheme("darkMode");
}
parseCookie(cookie : String)
function parseCookie(cookie) {
let match = [...cookie.matchAll(/(.*?)=(.*?)(?:;(?: |)|$)/gm)];
let cookieObject = {};
for(let i = 0; i < match.length; i++) {
cookieObject[match[i][1]] = match[i][2];
}
return cookieObject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment