Skip to content

Instantly share code, notes, and snippets.

@romanoffs
Last active May 26, 2019 11:22
Show Gist options
  • Save romanoffs/430a76d0be3327c704fbd49a8357e655 to your computer and use it in GitHub Desktop.
Save romanoffs/430a76d0be3327c704fbd49a8357e655 to your computer and use it in GitHub Desktop.
Get, Update, Set, Delete Cookie in TypeScript
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