Get cookie by name

Return cookie value by name. If not found return null

function getCookie(name) {
  		const value = `; ${document.cookie}`;
  		const parts = value.split(`; ${name}=`);
  		return (parts.length === 2) ? parts.pop().split(';').shift() : null;
}

Get all cookie names

function getAllCookieNames() {
    if (document.cookie == "") {
      return [];
    }
    let cookieNames = [];
    var a = document.cookie.split(";");
    for (let ii = 0; ii < a.length; ii++) {
        cookieNames.push(a[ii].split("=")[0].trim());
    }
    return cookieNames;
}

Set cookie by name, value and days

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

Erase cookie

function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

More info: https://www.quirksmode.org/js/cookies.html

Categories: Js,Ts,Css

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.