How can I create and read a value from a cookie in JavaScript?
Advertisement
Answer
Here are functions you can use for creating and retrieving cookies.
JavaScript
x
28
28
1
function createCookie(name, value, days) {
2
var expires;
3
if (days) {
4
var date = new Date();
5
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
6
expires = "; expires=" + date.toGMTString();
7
}
8
else {
9
expires = "";
10
}
11
document.cookie = name + "=" + value + expires + "; path=/";
12
}
13
14
function getCookie(c_name) {
15
if (document.cookie.length > 0) {
16
c_start = document.cookie.indexOf(c_name + "=");
17
if (c_start != -1) {
18
c_start = c_start + c_name.length + 1;
19
c_end = document.cookie.indexOf(";", c_start);
20
if (c_end == -1) {
21
c_end = document.cookie.length;
22
}
23
return unescape(document.cookie.substring(c_start, c_end));
24
}
25
}
26
return "";
27
}
28