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

当前回答

我写这篇文章是为了在Internet Explorer 11和现代浏览器(如Chromium Edge和Firefox)下工作。

这将获得一个HttpOnly属性为false的cookie值。

    function getCookieValue(keyName) {

        let returnValue = undefined;

        if (keyName && document.cookie) {

            let cookieArray = decodeURIComponent(document.cookie).split('; ');
            for (var i = 0; i < cookieArray.length; i++) {

                if (cookieArray[i]) {
                    let key = cookieArray[i].split('=')[0];
                    if (key && key === keyName) {
                        let value = cookieArray[i].split('=')[1];
                        returnValue = value;
                        break;
                    }
                }

            }

        }

        return returnValue;

    }

其他回答

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')

我更喜欢在cookie上使用一个正则表达式匹配:

window.getCookie = function(name) {
  var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  if (match) return match[2];
}

也可以作为函数使用,检查下面的代码。

function check_cookie_name(name) 
    {
      var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
      if (match) {
        console.log(match[2]);
      }
      else{
           console.log('--something went wrong---');
      }
   }

感谢Scott Jungwirth的评论。

在我的项目中,我使用以下函数按名称访问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);
}

其他一些使用正则表达式的答案中的方法并不涵盖所有情况,特别是:

当饼干是最后一块时。在这种情况下,cookie值后不会有分号。 当另一个cookie名称以正在查找的名称结束时。例如,您正在寻找名为“one”的cookie,而有一个名为“done”的cookie。 cookie名称中包含的字符在正则表达式中使用时不会被解释为字符本身,除非它们前面有反斜杠。

下面的方法可以处理这些情况:

function getCookie(name) {
    function escape(s) { return s.replace(/([.*+?\^$(){}|\[\]\/\\])/g, '\\$1'); }
    var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
    return match ? match[1] : null;
}

如果没有找到cookie,将返回null。如果cookie值为空,则返回空字符串。

注:

这个函数假设cookie名称是区分大小写的。 文档。cookie——当this出现在赋值的右侧时,它表示一个字符串,其中包含一个以分号分隔的cookie列表,这些cookie又是名称=值对。每个分号后面似乎都有一个空格。 String.prototype.match() -当没有找到匹配时返回null。找到匹配项时返回一个数组,索引[1]处的元素是第一个匹配组的值。

正则表达式

(?:xxxx) -组成不匹配的组。 ^ -匹配字符串的开头。 | -为组分离可选模式。 \\s* -匹配一个分号后面跟着零个或多个空格。 = -匹配一个等号。 (xxxx) -组成匹配组。 [^;]* -匹配零个或多个分号以外的字符。这意味着它将匹配最大(但不包括)分号或字符串末尾的字符。

通过名称获取cookie只需将cookie的名称传递给下面的函数

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.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 "";
}