views:

471

answers:

3

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
Can be problematic if you search BEL and there is a cookie named REBEL, no?
PhiLho
+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
Yea I have used quirksmode's get/set cookie code in the past as well.
EvilSyn
I would recommend quirksmode's cookie function as well.
Prestaul
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