« Wonders of keyword based advertising | Main | "Effective Java" or "Heads First Java" »

Found a bug in JavaScript Cookie class of JavaScript: The Definitive Guide

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:
    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];
This can be easily fixed by first replacing all blanks with zero length strings, as in:
    var cookies = allcookies.replace(" ", "").split(';');
My program is happy now.

Comments (3)


what happens if you have a space in the cookie value?

sherry william [TypeKey Profile Page]:

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

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(';');

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)


This page contains a single entry from the blog posted on January 12, 2007 6:16 AM.

The previous post in this blog was Wonders of keyword based advertising.

The next post in this blog is "Effective Java" or "Heads First Java".

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33