HTML and CSS Reference
In-Depth Information
To extract the field's value and store it in a variable named
fvalue
, use the
substring()
method
fvalue=cookies.substring(startvalue,ƒendvalue);
where
startvalue
indicates the start of the substring and
endvalue
marks the substring's
end. The complete readCookie() function looks as follows:
functionƒreadCookie(fname)ƒ{
ƒƒƒvarƒcookies=document.cookie;
ƒƒƒvarƒstartname=cookies.indexOf(fname+”=”);
ƒƒƒvarƒstartvalue=cookies.indexOf(“=”,ƒstartname)+1;
ƒƒƒvarƒendvalue=cookies.indexOf(“;”,startvalue);
ƒƒƒif(endvalue==-1)ƒ{
ƒƒƒƒƒendvalue=cookies.length;
ƒƒƒ}
ƒƒƒvarƒfvalue=cookies.substring(startvalue,ƒendvalue);
returnƒfvalue;
}
In a JavaScript program, calling the function
readCookie(“custid”);
would return a value of 20010, which is the customer id value stored in the cookie
file. You should review this example carefully, paying close attention to the use of the
indexOf( )
method and the
substring( )
method.
Encoding Cookies
Values in the cookie text string cannot contain spaces, semicolons, or commas. This can
be a problem if you are trying to store phrases or sentences. The solution to this problem
is to encode these values, using the same type of encoding scheme that is used in URLs
(which also cannot contain spaces, commas, and semicolons) or in the
mailto
action.
JavaScript includes the
escape( )
method for encoding your text strings. Encoding
replaces blank spaces, semicolons, and commas with special characters. For example, if
you want to insert an
Address
field in your cookie that contains a street number and an
address, you could use the following JavaScript command:
document.cookie='Address='+escape(document.Orders.Address.value);
To read a text string that has been encoded, you use JavaScript's
unescape( )
method.
For example, you could replace the command that stores the field value in the
fvalue
variable in the readCookie( ) function with the following command:
varƒfvalue=unescape(cookies.substring(startvalue,ƒendvalue));
This command removes any encoding characters and replaces them with the appropriate
spaces, semicolons, commas, and so forth.