简体   繁体   中英

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 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.

In case anyone else needs it, I've fixed up Diodeus's code to address PhiLho's concern about partial matches when trying to fetch a cookie value.

function getCookie(c_name) {
    var nameEQ = c_name + '=';
    var c_start = 0;
    var c_end = 0;
    if (document.cookie.substr(0, nameEQ.length) === nameEQ) {
        return document.cookie.substring(nameEQ.length, document.cookie.indexOf(';', nameEQ.length));
    } else {
        c_start = document.cookie.indexOf('; ' + nameEQ);
        if(c_start !== -1){
            c_start += nameEQ.length + 2;
            c_end = document.cookie.indexOf(';', c_start);
            if (c_end === -1) {c_end = document.cookie.length;}
            return document.cookie.substring(c_start, c_end);
        }
    }
    return null;
}

I've recently also built a much more compact RegExp that should work as well:

function getCookie(c_name){
    var ret = window.testCookie.match(new RegExp("(?:^|;)\\s*"+c_name+"=([^;]*)"));
    return (ret !== null ? ret[1] : null);
}

I did some speed tests that seem to indicate that out of PhiLo, QuirksMode, and these two implementations the non-RegExp version (using indexOf is very fast, not a huge surprise) above is the fastest. http://jsperf.com/cookie-fetcher

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM