按名称获取Cookie

本文翻译自:Get cookie by name

I have a getter to get the value from a cookie. 我有一个吸气剂来从cookie中获取价值。

Now I have 2 cookies by the name shares= and by the name obligations= . 现在,我有2个Cookie,名称分别为shares=obligations=

I want to make this getter only to get the values from the obligations cookie. 我只想让这个吸气剂从义务cookie中获取值。

How do I do this? 我该怎么做呢? So the for splits the data into separate values and puts it in an array. 因此, 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]);
    }
 }

#1楼

参考:https://stackoom.com/question/j1SM/按名称获取Cookie


#2楼

use a cookie getting script: 使用Cookie获取脚本:

function readCookie(name) {
    var nameEQ = name + "=";
    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,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

then call it: 然后调用它:

var value = readCookie('obligations');

i stole the code above from quirksmode cookies page. 我从quirksmode cookie页面上偷了上面的代码。 you should read it . 你应该读它 。


#3楼

It seems to me you could split the cookie key-value pairs into an array and base your search on that: 在我看来,您可以将Cookie键值对拆分为一个数组,然后基于该数组进行搜索:

var obligations = getCookieData("obligations");

Which runs the following: 运行以下命令:

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

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

Or possibly even the following: 甚至可能是以下情况:

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

#4楼

One approach, which avoids iterating over an array, would be: 一种避免迭代数组的方法是:

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

Walkthrough 演练

Splitting a string by token will produce either, an array with one string (same value), in case token does not exist in a string, or an array with two strings , in case token is found in a string . 如果令牌中不存在令牌,则按令牌拆分字符串将生成一个具有一个字符串(相同值)的数组,或者如果在string中找到令牌,则将生成具有两个字符串的数组。

The first (left) element is string of what was before the token, and the second one (right) is what is string of what was after the token. 第一个(左)元素是令牌之前的字符串,第二个(右)元素是令牌之后的字符串。

(NOTE: in case string starts with a token, first element is an empty string) (注意:如果字符串以令牌开头,则第一个元素为空字符串)

Considering that cookies are stored as follows: 考虑到cookie的存储方式如下:

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

in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";". 为了检索特定的cookie值,我们只需要获取在“; {name} =”之后和下一个“;”之前的字符串。 Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=": 在进行任何处理之前,我们在cookie字符串前添加“;”,以便每个cookie名称(包括第一个)都用“;”和“ =“括起来:

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

Now, we can first split by "; {name}=", and if token is found in a cookie string (ie we have two elements), we will end up with second element being a string that begins with our cookie value. 现在,我们首先可以用“; {name} =”进行拆分,如果在cookie字符串中找到了令牌(即,我们有两个元素),我们将以第二个元素作为以cookie值开头的字符串结尾。 Then we pull that out from an array (ie pop), and repeat the same process, but now with ";" 然后我们将其从数组中取出(即pop),并重复相同的过程,但现在使用“;” as a token, but this time pulling out the left string (ie shift) to get the actual token value. 作为令牌,但是这次拉出左字符串(即shift)以获取实际令牌值。


#5楼

In my projects I use following function to access cookies by name 在我的项目中,我使用以下功能按名称访问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);
}

#6楼

I would prefer using a single regular expression match on the cookie: 我希望在Cookie上使用单个正则表达式匹配项:

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

OR Also we are able to use as a function , check below code. 或者我们也可以将其用作函数,请检查以下代码。

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

Improved thanks to Scott Jungwirth in the comments. 由于评论中的Scott Jungwirth而有所改进。

你可能感兴趣的:(javascript,cookies)