我有一个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 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()函数以获取它的值

其他回答

我更喜欢在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的评论。

参考:https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

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

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

  alert(cookieValue);

我写这篇文章是为了在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;

    }

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

当饼干是最后一块时。在这种情况下,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) -组成匹配组。 [^;]* -匹配零个或多个分号以外的字符。这意味着它将匹配最大(但不包括)分号或字符串末尾的字符。

我会这样做:

function getCookie(cookie){
  return cookie
    .trim()
    .split(';')
    .map(function(line){return line.split(',');})
    .reduce(function(props,line) {
      var name = line[0].slice(0,line[0].search('='));
      var value = line[0].slice(line[0].search('='));
      props[name] = value;
      return props;
    },{})
}

这将以对象的形式返回cookie。

然后你可以这样调用它:

getCookie(document.cookie)['shares']