Java Reference
In-Depth Information
cookieValue = escape(cookieValue);
if (cookieExpires == “”)
{
var nowDate = new Date();
nowDate.setMonth(nowDate.getMonth() + 6);
cookieExpires = nowDate.toGMTString();
}
if (cookiePath != “”)
{
cookiePath = “;Path=” + cookiePath;
}
document.cookie = cookieName + “=” + cookieValue +
“;expires=” + cookieExpires + cookiePath;
}
The
secure
and
domain
parts of the cookie string are unlikely to be needed, so you allow just the
name
,
value
,
expires
, and
path
parts of a cookie to be set by the function. If you don't want to set a path or
expiration date, you just pass empty strings for those parameters. If no path is specifi ed, the current
directory and its subdirectories will be the path. If no expiration date is set, you just assume a date six
months from now.
The fi rst line of the function introduces the
escape()
function, which you've not seen before.
cookieValue = escape(cookieValue);
When we talked about setting the value of a cookie, we mentioned that certain characters cannot be used
directly, such as a semicolon. (This also applies to the name of the cookie.) To get around this problem,
you can use the built-in
escape()
and
unescape()
functions. The
escape()
function converts charac-
ters that are not text or numbers into the hexadecimal equivalent of their character in the Latin-1
character set, preceded by a
%
character.
For example, a space has the hexadecimal value
20
, and the semicolon the value
3B
. So the following
code produces the output shown in Figure 11-11:
alert(escape(“2001 a space odyssey;”));
Figure 11-11
You can see that each space has been converted to %20, the % indicating that it represents an escape or
special character rather than an actual character, and that 20 is the ASCII value of the actual character.
The semicolon has been converted to %3B, as you'd expect.