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

当前回答

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

其他回答

显然,MDN从未听说过单词边界正则表达式字符类\b,它与相邻的\w+相匹配,而\w+在两侧有界:

getCookie = function(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : null;
};

var obligations = getCookie('obligations');

一种避免在数组上迭代的方法是:

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

预排

如果字符串中不存在令牌,则通过令牌分割字符串将生成一个包含一个字符串(相同值)的数组;如果字符串中存在令牌,则生成一个包含两个字符串的数组。

第一个(左)元素是标记之前的字符串,第二个(右)元素是标记之后的字符串。

(注意:如果字符串以令牌开头,第一个元素为空字符串)

考虑到cookie的存储方式如下:

"{name}={value}; {name}={value}; ..."

为了检索特定的cookie值,我们只需要获取“;”之后的字符串;{name}=" and before next ";"。在进行任何处理之前,在cookie字符串前加上";,这样每个cookie名称,包括第一个,都包含“;And "=":

"; {name}={value}; {name}={value}; ..."

现在,我们可以先用";{name}=",如果token在一个cookie字符串中找到(即我们有两个元素),我们将以第二个元素为以我们的cookie值开头的字符串结束。然后我们从数组中取出它(即pop),并重复相同的过程,但现在使用“;”作为标记,但这次取出左边的字符串(即shift)以获得实际的标记值。

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键值对分成一个数组,并基于你的搜索:

var obligations = getCookieData("obligations");

运行如下:

function getCookieData( name ) {
    var pairs = document.cookie.split("; "),
        count = pairs.length, parts; 
    while ( count-- ) {
        parts = pairs[count].split("=");
        if ( parts[0] === name )
            return parts[1];
    }
    return false;
}

小提琴:http://jsfiddle.net/qFmPc/

或者甚至可能是以下内容:

function getCookieData( name ) {
    var patrn = new RegExp( "^" + name + "=(.*?);" ),
        patr2 = new RegExp( " " + name + "=(.*?);" );
    if ( match = (document.cookie.match(patrn) || document.cookie.match(patr2)) )
        return match[1];
    return false;
}

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