Skip to content

Instantly share code, notes, and snippets.

@elpuas
Created January 9, 2023 16:41
Show Gist options
  • Save elpuas/0bd03850132f25051cd6104561051b4a to your computer and use it in GitHub Desktop.
Save elpuas/0bd03850132f25051cd6104561051b4a to your computer and use it in GitHub Desktop.
Set and Get Cookies
/**
* Set a cookie
*
* @param {string} name - The name of the cookie.
* @param {string} value - The value of the cookie.
* @param {number} [days] - The number of days until the cookie expires.
*/
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.toUTCString();
}
document.cookie = name + '=' + ( value || '' ) + expires + '; path=/';
};
/**
* Returns the value of a cookie with the specified name.
*
* @param {string} name - The name of the cookie.
* @return {string} The value of the cookie, or an empty string if the cookie does not exist.
*/
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 '';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment