Skip to content

Instantly share code, notes, and snippets.

@HichamBenjelloun
Last active June 25, 2020 18:27
Show Gist options
  • Save HichamBenjelloun/dc2091d2ea2410d03561db4016797cce to your computer and use it in GitHub Desktop.
Save HichamBenjelloun/dc2091d2ea2410d03561db4016797cce to your computer and use it in GitHub Desktop.
A function that parses a string representation of a list of cookies into an object
const SEP_KEYVAL = '='; // represents a separator between a key and the corresponding value
const SEP_COOKIES = ';'; // represents a separator between two adjacent cookies
const parseKeyValuePair = keyValuePairStr => {
const [key, value] =
keyValuePairStr
.trimStart()
.split(SEP_KEYVAL);
return [key, decodeURIComponent(value)];
};
const parseCookies = cookiesStr => { // parses a standard cookie list string representation
const cookieEntries =
cookiesStr
.split(SEP_COOKIES)
.map(parseKeyValuePair);
return Object.fromEntries(cookieEntries);
}
export default parseCookies;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment