我有一个getter从cookie中获取值。

现在我有了两个cookie,名字分别是shares=和obligation =。

我想让这个getter只从义务cookie中获取值。

我怎么做呢?因此for语句将数据拆分为单独的值,并将其放入数组中。

 function getCookie1() {
    // What do I have to add here to look only in the "obligations=" cookie? 
    // Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }

当前回答

这个方法开箱即用,效果非常好

function getCookie(cname) {
  var cookies = ` ${document.cookie}`.split(";");
  var val = "";
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].split("=");
    if (cookie[0] == ` ${cname}`) {
      return cookie[1];
    }
  }
  return "";
}

其他回答

The Document property cookie lets you read and write cookies associated with the document. It serves as a getter and setter for the actual values of the cookies.
var c = 'Yash' + '=' + 'Yash-777';
document.cookie = c; // Set the value: "Yash=Yash-777"
document.cookie      // Get the value:"Yash=Yash-777"

来自谷歌GWT项目cookie .java类本机代码。我准备了以下函数来对Cookie执行操作。

函数以JSON对象的形式获取所有cookie列表。

var uriEncoding = false;
function loadCookiesList() {
    var json = new Object();
    if (typeof document === 'undefined') {
        return json;
    }

    var docCookie = document.cookie;
    if (docCookie && docCookie != '') {
      var crumbs = docCookie.split('; ');
      for (var i = crumbs.length - 1; i >= 0; --i) {
        var name, value;
        var eqIdx = crumbs[i].indexOf('=');
        if (eqIdx == -1) {
          name = crumbs[i];
          value = '';
        } else {
          name = crumbs[i].substring(0, eqIdx);
          value = crumbs[i].substring(eqIdx + 1);
        }
        if (uriEncoding) {
          try {
            name = decodeURIComponent(name);
          } catch (e) {
            // ignore error, keep undecoded name
          }
          try {
            value = decodeURIComponent(value);
          } catch (e) {
            // ignore error, keep undecoded value
          }
        }
        json[name] = value;
      }
    }
    return json;
 }

设置并获取具有特定名称的Cookie。

function getCookieValue(name) {
    var json = loadCookiesList();
    return json[name];
}

function setCookie(name, value, expires, domain, path, isSecure) {
    var c = name + '=' + value;
    if ( expires != null) {
        if (typeof expires === 'number') {
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
            var timeInMs = Date.now();
            if (expires > timeInMs ) {
                console.log("Seting Cookie with provided expire time.");
                c += ';expires=' + (new Date(expires)).toGMTString();
            } else if (expires < timeInMs) {
                console.log("Seting Cookie with Old expire time, which is in Expired State.");
                timeInMs = new Date(timeInMs + 1000 * expires);
                c += ';expires=' + (new Date(timeInMs)).toGMTString();
            }
        } else if (expires instanceof window.Date) {
            c += ';expires=' + expires.toGMTString();
        }
    }

    if (domain != null && typeof domain == 'string')
      c += ';domain=' + domain;
    if (path != null && typeof path == 'string')
      c += ';path=' + path;
    if (isSecure != null && typeof path == 'boolean')
      c += ';secure';

    if (uriEncoding) {
        encodeURIComponent(String(name))
            .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
            .replace(/[\(\)]/g, escape);
        encodeURIComponent(String(value))
            .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);

    }
    document.cookie = c;
}

function removeCookie(name) {
    document.cookie = name + "=;expires=Fri, 02-Jan-1970 00:00:00 GMT"; 
}
function removeCookie(name, path) {
    document.cookie = name + "=;path=" + path + ";expires=Fri, 02-Jan-1970 00:00:00 GMT";
}

检查cookie名称是否有效:不能包含'=',';',','或空格。不能以$开头。

function isValidCookieName(name) {
    if (uriEncoding) {
      // check not necessary
      return true;
    } else if (name.includes("=") || name.includes(";") || name.includes(",") || name.startsWith("$") || spacesCheck(name) ) {
      return false;
    } else {
      return true;
    }
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
function spacesCheck(name) {
    var whitespace = new RegExp('.*\\s+.*');
    var result = whitespace.test(name);
    console.log("Name:isContainSpace = ", name, ":", result);
    return result;
}

测试步骤检查以上功能:

setCookie("yash1", "Yash-777");
setCookie("yash2", "Yash-Date.now()", Date.now() + 1000 * 30);
setCookie("yash3", "Yash-Sec-Feature", 30);
setCookie("yash4", "Yash-Date", new Date('November 30, 2020 23:15:30'));

getCookieValue("yash4"); // Yash-Date
getCookieValue("unknownkey"); // undefined

var t1 = "Yash", t2 = "Y    ash", t3 = "Yash\n";
spacesCheck(t1); // False
spacesCheck(t2); // True
spacesCheck(t3); // True

在我的项目中,我使用以下函数按名称访问cookie

function getCookie(cookie) {
    return document.cookie.split(';').reduce(function(prev, c) {
        var arr = c.split('=');
        return (arr[0].trim() === cookie) ? arr[1] : prev;
    }, undefined);
}
function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

将cookie名称传递给getCookie()函数以获取它的值

我知道这是一个老问题,但我也遇到过这个问题。只是为了记录,在开发者的mozilla网页中有一个小API。

你可以只使用JS获得任何名称的cookie。恕我直言,代码也更干净(除了很长的代码行,我相信您可以很容易地修改)。

function getCookie(sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
}

如注释中所述,注意此方法假定键和值是使用encodeURIComponent()编码的。如果cookie的键和值没有被编码,则删除decode & encodeURIComponent()。

现在,当以数组格式存储cookie时,可以让cookie以数组形式返回。 例如,你的cookie数组[35]=Khóa;数组[36]= Tử;数组[37]= Cử; 这段代码也包含utf8。 当你的cookie名称内容[]在其中,而你存储的cookie不在数组中时,一件事不会很好地工作。

function getCookie(cname) {

            var ca = decodeURIComponent(document.cookie).split(';');


            if (cname.indexOf('[]') > 0) {
                var returnVAlue = [];
                var nameArray = cname.replace("[]", "");

                for(var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                   // console.log(c);
                    while (c.charAt(0) == ' ') {
                        c = c.substring(1);
                    }

                    if (c.indexOf(nameArray) >= 0) {
                        var valueString = c.substr(nameArray.length, c.length);

                        var valueStringSlit = valueString.split('=');
                        valueStringSlit[0] = valueStringSlit[0].substr(1,(valueStringSlit[0].length - 2));
                    //    console.log(valueStringSlit);

                        returnVAlue.push(valueStringSlit);
                    }
                }
            } else {
                var returnVAlue = '';
                var name = cname + "=";

                for(var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                   // console.log(c);
                    while (c.charAt(0) == ' ') {
                        c = c.substring(1);
                    }
                    if (c.indexOf(name) == 0) {
                        returnVAlue = c.substr(name.length, c.length);
                    } 
                }
            }


            if (returnVAlue != ''){
                return returnVAlue;
            } 
            return "";
        }

       // console.log(decodeURIComponent(document.cookie));


        console.log(getCookie('array[]'));