Jump to content
Larry Ullman's Book Forums
Sign in to follow this  

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:














Share this post

Link to post
Share on other sites

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.

Share this post

Link to post
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?

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Create New...