diff --git a/snippets/parseCookie.md b/snippets/parseCookie.md new file mode 100644 index 000000000..88e12860a --- /dev/null +++ b/snippets/parseCookie.md @@ -0,0 +1,16 @@ +### parseCookie + +Parse an HTTP Cookie header string and return an object of all cookie name-value pairs. + +Use `String.split(';')` to separate key-value pairs from each other. +Use `Array.map()` and `String.split('=')` to separate keys from values in each pair. +Use `Array.reduce()` and `decodeURIComponent()` to create an object with all key-value pairs. + +```js +const parseCookie = str => + str.split(';').map(v => v.split('=')).reduce((acc,v) => {acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); return acc},{}); +``` + +```js +parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' } +``` diff --git a/snippets/serializeCookie.md b/snippets/serializeCookie.md new file mode 100644 index 000000000..4b434351f --- /dev/null +++ b/snippets/serializeCookie.md @@ -0,0 +1,13 @@ +### serializeCookie + +Serialize a cookie name-value pair into a Set-Cookie header string. + +Use template literals and `encodeURIComponent()` to create the appropriate string. + +```js +const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; +``` + +```js +serializeCookie('foo', 'bar'); // 'foo=bar' +``` diff --git a/tag_database b/tag_database index e1d4aa6aa..87c97fcd1 100644 --- a/tag_database +++ b/tag_database @@ -125,6 +125,7 @@ once:function onUserInputChange:browser,event,advanced orderBy:object,array palindrome:string +parseCookie:utility,string partition:array,object,function percentile:math pick:array @@ -154,6 +155,7 @@ sampleSize:array,random scrollToTop:browser sdbm:math,utility select:object +serializeCookie:utility,string setStyle:browser shallowClone:object show:browser,css