我有一个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(name) {
    var pair = document.cookie.split('; ').find(x => x.startsWith(name+'='));
    if (pair)
       return pair.split('=')[1]
}

其他回答

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

Kirlich给出了一个很好的解决方案。然而,当有两个cookie值具有相似的名称时,它会失败,这里有一个简单的修复这种情况:

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length >= 2) return parts.pop().split(";").shift();
}

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

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)以获得实际的标记值。

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

关于如何得到饼干,这里已经有了很好的答案,但这是我自己的解决方案:

function getcookie(cookiename){
var cookiestring  = document.cookie;
var cookiearray = cookiestring.split(';');
for(var i =0 ; i < cookiearray.length ; ++i){ 
    if(cookiearray[i].trim().match('^'+cookiename+'=')){ 
        return cookiearray[i].replace(`${cookiename}=`,'').trim();
    }
} return null;
}

用法:“

     getcookie('session_id');
   // gets cookie with name session_id