Last active
May 26, 2019 11:22
-
-
Save romanoffs/430a76d0be3327c704fbd49a8357e655 to your computer and use it in GitHub Desktop.
Get, Update, Set, Delete Cookie in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static getCookie(name: string): string { | |
const matches = document.cookie.match(new RegExp( | |
'(?:^|; )' + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + '=([^;]*)' | |
)); | |
return matches ? decodeURIComponent(matches[1]) : undefined; | |
} | |
static setCookie(name: string, value: string, props: any = {}): void { | |
let exp: Date | number = props.expires; | |
if (typeof exp === 'number' && exp) { | |
const d = new Date(); | |
d.setTime(d.getTime() + exp * 1000); | |
exp = props.expires = d; | |
} | |
if (exp && typeof exp !== 'number' && exp.toUTCString) { | |
props.expires = exp.toUTCString(); | |
} | |
value = encodeURIComponent(value); | |
let updatedCookie = name + '=' + value; | |
for (let propName in props) { | |
updatedCookie += '; ' + propName; | |
const propValue = props[propName]; | |
if (propValue !== true) { | |
updatedCookie += '=' + propValue; | |
} | |
} | |
document.cookie = updatedCookie; | |
} | |
static deleteCookie(name: string): void { | |
return Utils.setCookie(name, null, {expires: -1}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment