Friday, February 11, 2011

What is the best way to get a cookie by name in JavaScript?

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?

  • 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 ""
    

    }

    PhiLho : Can be problematic if you search BEL and there is a cookie named REBEL, no?
    From Diodeus
  • 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.

    EvilSyn : Yea I have used quirksmode's get/set cookie code in the past as well.
    Prestaul : I would recommend quirksmode's cookie function as well.
  • 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.

    From PhiLho

0 comments:

Post a Comment