我有一个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]);
    }
 }

当前回答

我修改了Jonathan在这里提供的函数,通过使用正则表达式,你可以通过它的名字获得一个cookie值,就像这样:

function getCookie(name){
    var pattern = RegExp(name + "=.[^;]*")
    var matched = document.cookie.match(pattern)
    if(matched){
        var cookie = matched[0].split('=')
        return cookie[1]
    }
    return false
}

如果返回空字符串,则表示cookie存在但没有值,如果返回false则表示cookie不存在。我希望这能有所帮助。

其他回答

现在,当以数组格式存储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[]'));

JS中的Set-Cookie

document.cookie = 'fb-event-id=15648779++';

通过名称函数获取cookie

function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");
    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");
        /* Removing whitespace at the beginning of the cookie name
        and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    } 
    // Return null if not found
    return null;
}

这是如何使用getCookie函数

var eventID = getCookie('fb-event-id')

只是为了给这个响应添加一个“正式”的答案,我复制/粘贴解决方案来设置和从MDN检索cookie(这里是JSfiddle

    document.cookie = "test1=Hello";
    document.cookie = "test2=World";

    var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");

    function alertCookieValue() {
      alert(cookieValue);
    }

在您的特定情况下,您将使用以下函数

    function getCookieValue() {
      return document.cookie.replace(/(?:(?:^|.*;\s*)obligations\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    }

注意,我只是用“义务”替换了示例中的“test2”。

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

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

我知道这是一个老问题,但我也遇到过这个问题。只是为了记录,在开发者的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()。