sonal Posted April 16, 2012 Share Posted April 16, 2012 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 More sharing options...
Larry Posted April 16, 2012 Share Posted April 16, 2012 Could you start by confirming the use of quotes or not quotes in your values? In your example, you quote one value but not the others. Link to comment Share on other sites More sharing options...
sonal Posted April 17, 2012 Author Share Posted April 17, 2012 Thanks for looking Larry. I edited my post to show that cookie is set properly with value in quotes. Link to comment Share on other sites More sharing options...
Larry Posted April 19, 2012 Share Posted April 19, 2012 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 More sharing options...
Recommended Posts