Jump to content
Larry Ullman's Book Forums

Slicing Cookie Values Give Problems


Recommended Posts

I'm trying to read multiple cookie values as per the example given in the Larry's new book, on page 362. I'm experiencing difficulties for slice function on step 6. This problem is particularly about the code in the book. I used code from w3schools example, and it works fine. But I in my college assignment, I have to use split and slice methods to read cookies. So I'm experimenting with the code given in the book.

 

This book's code (simplified version) is like this:

 

function getCookie(name) {

var len = name.length;

var cookies = document.cookie.split(';');

for(var i =0; count = cookies.length; i < count; i++) {

var value = (cookies.slice(0,1) == ' ') ? cookies.slice(1) : cookies;

if(value.slice(0,len) == name) {

return cookies.split('=')[1];

}

}

return false;

}

 

 

In one of my problems, I'm setting 3 cookies in document.cookie: Like this:

document.cookie = 'fName=son';

document.cookie = 'lName=pat';

document.cookie = 'email=sp@d.com'

 

I can say that cookies get set as per given values. I check them in browsers cookie settings.

 

everything works fine until I read first cookie (fName). But the example then never reads from second cookie. To read these cookies, I'm using statements like : COOKIE.getCookie('fName') //This returns right cookie value.

COOKIE.getCookie('lName') //This never returns cookie value.

 

 

I'm trying to figure out where is the problem using firebug console. It shows that second cookie name gets sliced off for one character less than its value.

That is,

if(value.slice(0, len) == name) // This sentence slice off value to len-1 characters. {

return ....

}

 

firebug console response for console.log(value.slice(0,len)); inside the loop:

 

fName

 

 

lName=mol

 

 

lNam

 

 

email=pmol@mycompany.com

 

emai

Link to comment
Share on other sites

Okay, so it sounds like you're doing good detective work here. I don't quite understand your output from using console.log(), though. Could you clarify that? Also, what specific browser(s) are you having this cookie problem in?

Link to comment
Share on other sites

 Share

×
×
  • Create New...