I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript?
A:
I use this. It has been dependable:
function getCookie(c_name) {
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
Diodeus
2008-09-25 20:32:44
Can be problematic if you search BEL and there is a cookie named REBEL, no?
PhiLho
2008-10-07 20:13:33
+2
A:
Anytime I need to access it, I use document.cookie, basically how it's outlined in that article. Caveat, I've never used prototype, so there may be easier methods there that you just haven't run across.
Pseudo Masochist
2008-09-25 20:32:56
A:
I use this routine:
function ReadCookie(name)
{
name += '=';
var parts = document.cookie.split(/;\s*/);
for (var i = 0; i < parts.length; i++)
{
var part = parts[i];
if (part.indexOf(name) == 0)
return part.substring(name.length)
}
return null;
}
Works quite well.
PhiLho
2008-10-07 20:30:02