Skip to content

Instantly share code, notes, and snippets.

@rahulsprajapati
Created August 8, 2022 16:04
Show Gist options
  • Save rahulsprajapati/b3e97e6dd7bc9553e54f70cb6ca28c27 to your computer and use it in GitHub Desktop.
Save rahulsprajapati/b3e97e6dd7bc9553e54f70cb6ca28c27 to your computer and use it in GitHub Desktop.
Cookies Set and Get for Javascript.
// Setcookie.
export const setCookie = (name, value, days) => {
let expires = '';
if (days) {
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = `; expires=${date.toGMTString()}`;
}
document.cookie = `${name}=${value}${expires}; path=/`;
};
// Getcookie.
export const getCookie = (name) => {
const nameEQ = `${name}=`;
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment