[javascript] 쿠키(cookie)셋팅 expires 쉽게 설정하기 (getCookie, setCookie)

자바스크립트에서 쿠키셋팅시 expires을 일수로 설정할수 있는 함수이다.

예) setCookie('CookieName', CookieValue', 365); //365일 후 만료
var str = getCookie('CookieName');

 

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

 

function getCookie(name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        
        for (i = 0; i < ARRcookies.length; i++) {     
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                
                x = x.replace(/^\s+|\s+$/g, "");

                if (x == name) {
                        return unescape(y);
                }
        }
}

 

댓글

Designed by JB FACTORY