W3Schools에서는 아래와 같이 쿠키를 불러오라고 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

그러나 내가 보기에는 너무나 길었다.(???)
그래서 줄여보았다.

1
2
3
4
5
function getCookie(cname){
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
return decodedCookie.substring(decodedCookie.indexOf(name)+name.length,decodedCookie.length).split(' ;')[0];
}

아직까지는 그나마 양심적이다. (???)
사실 이 코드의 문제는 절대로 key-value구조인 Cookie에서 key와 value에 =까지 같은 값이 없어야 한다는 점이다. 예를들면 key값을 answer이라고 하자. 저 소스를 그대로 쓰면 abc=answer= 이런 형식의 쿠키에서 걸리기 때문에 터지게 된다. 그렇지만 저런일이 없다면 써도 될 것이다. (value값에 =을 안넣으면 된다!)

1
2
3
4
function getCookie(name){
let dc = decodeURIComponent(document.cookie);
return dc.substring(dc.indexOf(name) + name.length + 1).split(';')[0];
}

더 줄여보았다. 이제 슬슬 양심이 사라지고(???) 막장으로 가는 코드열차가 출발했다. 이젠 value에 name이 있어선 안된다. 한마디로 말해서 key가 true인게 있다면, abc=true이런식의 쿠키는 저장하면 안된다! (key값을 valie값에서도 유니크하게 저장하면 된다.)

1
2
3
function getCookie(name){
return document.cookie.substring(document.cookie.indexOf(name+'=')).split(';')[0].split('=')[1]
}

유감스럽게도 이번이 마지막이다. 이런 코드는 정말 쓰면 안된다.(???) 써도 되는데, 주의할 필요가 있다. 일단 이코드는 escape를 안한다! 한마디로 말해서 저장할 때도 esacpe를 하면 안되기 때문에 신경을 써야한다. (…)

1
2
setCookie: (name, data) => document.cookie = `${name}=${data}; path=/ ;expires=2099-12-31T00:00:00.000Z;`,
loadCookie: name => document.cookie.substring(document.cookie.indexOf(name+'=')).split(';')[0].split('=')[1],

참고로 위의 코드는 https://earthquake.kr의 소스다. (은근슬쩍 홍보) 자동으로 이마를 짚게 해주는 훌륭한 코드다!