Hoping to save some time, I decided to use the JavaScript Cookie class provided in the otherwise excellent book JavaScript: The Definitive Guide, 5th Edition. However, my program was not working as intended -- the cookies that were supposed to last the whole session were getting reset at every new page. After an hour of
alert()
and FireBug assisted debugging finally helped me to track down the problem: the Cookie class was not behaving properly.
Just submitted an errata to O'reilly's. Here is the submission:
document.cookie value on FireFox includes a blank space after ';'. As a result, the code to extract a particular cookie value doesn't work:My program is happy now.var cookies = allcookies.split(';'); var cookie = null; for(var i = 0; i < cookies.length; i++) { // Does this cookie string begin with the name we want? if (cookies[i].substring(0, name.length+1) == (name + "=")) { cookie = cookies[i]; break; } }This can be easily fixed by first replacing all blanks with zero length strings, as in:var cookies = allcookies.replace(" ", "").split(';');
Comments (3)
what happens if you have a space in the cookie value?
Posted by Jason | January 12, 2007 5:42 PM
Posted on January 12, 2007 17:42
this is a very nice and informative site and i have found some useful information over here. i have developed a useful link,ccna provides you with some interesting information that can be useful to you and you can avail a lot. thanks
Posted by sherry william | May 30, 2010 11:29 PM
Posted on May 30, 2010 23:29
Your fix does not actually work if there are multiple cookies set, as it only replaces the first space in the allcookies string.
Instead, try:
var cookies = allcookies.replace(/ /g, "").split(';');
Posted by Jonathanberger | February 28, 2011 1:15 AM
Posted on February 28, 2011 01:15