[thelist] JS cookie question (ignore previous)

Hans-Fr=?ISO-8859-1?B?6WTp?=ric Fraser hfraser at videotron.ca
Fri Jan 10 14:22:01 CST 2003


On 1/10/03 2:23 PM, "Tom Dell'Aringa" <pixelmech at yahoo.com> wrote:
>> function getCookieData(whatCookie){
>>     var myCookie = new String(document.cookie);
>>     var myCookieHeader = whatCookie+"=";
>>     var myCookieStart = myCookie.indexOf(myCookieHeader);
>>     var myCookieEnd = myCookie.indexOf(';',myCookieStart);
>>
>>     // if there is only one cokie you do not have the semicolon at
>> the end
>>     if (myCookieEnd == -1){
>>         myCookieEnd = myCookie.length;
>>     }
>>     // extract data and check if the cookie exist
>>     if( myCookie.indexOf(myCookieHeader) != -1){
>>         myCookieStart = myCookieHeader.length;
>>         return myCookie.substring(myCookieStart, myCookieEnd);
>>         }
>>     else{
>>         // if the cookie does not exist well ... do what ever you
>> want
>>         return 'noCookie';
>>     }
>> }
>>
>> have fun!
>
> This function seems to give me the WHOLE cookie (or at least, the
> cookie up to the value of the supplied parameter). What I need is
> only the cookie value of the label I specify, If I specify pid114 for
> the cookie pid114=3, then I want ONLY that returned, not the whole
> string.

yeah your right :
change
var myCookieStart = myCookie.indexOf(myCookieHeader);
for
var myCookieStart = myCookie.indexOf(myCookieHeader) +
myCookieHeader.length;

> Can I fix my original function to do that? (You said I have a problem
> with the =)

yes:

> function getCookieData(labelName){
>   var labelLen = labelName.length;
>   // read cookie property only once for speed
>   var cookieData = document.cookie;
>   var cLen =  cookieData.length;
>   var i = 0;
>   var cEnd;
>
>   while(i < cLen){
>       var j = i + labelLen;
>       if(cookieData.substring(i,j) == labelName){
>           cEnd = cookieData.indexOf(";", j);
>           if(cEnd == -1){
>               cEnd = cookieData.length;
>           }
>           return unescape(cookieData.substring(j+1, cEnd));
>       }
>       i++
>   }
>   return "";
> }

you need to change :
labelName = labelName+"=";
var labelLen = labelName.length;

but your while loop is totaly overkill
you could just use indexOf() as long as you keep your = sign after the
labelName you will not get unwanted values!

why parse the whole thing ove and over again when you can just extract what
you need!


hans!




More information about the thelist mailing list