Get cookie by name

2018-12-31 10:14发布

I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to make this getter only to get the values from the obligations cookie.

How do I do this? So the 'for' splits the data into separate values and puts it in an array.

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

30条回答
君临天下
2楼-- · 2018-12-31 10:59

It seems to me you could split the cookie key-value pairs into an array and base your search on that:

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/

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;
}
查看更多
梦醉为红颜
3楼-- · 2018-12-31 10:59

Apparently MDN has never heard of the word-boundary regex character class \b, which matches contiguous \w+ that is bounded on either side with \W+:

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

var obligations = getCookie('obligations');
查看更多
孤独总比滥情好
4楼-- · 2018-12-31 10:59

Cookies example: example JS:

document.cookies = {
   create : function(key, value, time){
     if (time) {
         var date = new Date();
         date.setTime(date.getTime()+(time*24*60*60*1000));
         var expires = "; expires="+date.toGMTString();
     }
     else var expires = "";
     document.cookie = key+"="+value+expires+"; path=/";
   },
   erase : function(key){
     this.create(key,"",-1);
   },
   read : function(key){
     var keyX = key + "=";
     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(keyX) == 0) return   c.substring(keyX.length,c.length);
     }
     return null;
   }
}

Store arrays and objects with json or xml

查看更多
明月照影归
5楼-- · 2018-12-31 11:01

use a cookie getting script:

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. you should read it.

查看更多
浮光初槿花落
6楼-- · 2018-12-31 11:01

The methods in some of the other answers that use a regular expression do not cover all cases, particularly:

  1. When the cookie is the last cookie. In this case there will not be a semicolon after the cookie value.
  2. When another cookie name ends with the name being looked up. For example, you are looking for the cookie named "one", and there is a cookie named "done".
  3. When the cookie name includes characters that are not interpreted as themselves when used in a regular expression unless they are preceded by a backslash.

The following method handles these cases:

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

This will return null if the cookie is not found. It will return an empty string if the value of the cookie is empty.

Notes:

  1. This function assumes cookie names are case sensitive.
  2. document.cookie - When this appears on the right-hand side of an assignment, it represents a string containing a semicolon-separated list of cookies, which in turn are name=value pairs. There appears to be a single space after each semicolon.
  3. String.prototype.match() - Returns null when no match is found. Returns an array when a match is found, and the element at index [1] is the value of the first matching group.

Regular Expression Notes:

  1. (?:xxxx) - forms a non-matching group.
  2. ^ - matches the start of the string.
  3. | - separates alternative patterns for the group.
  4. ;\\s* - matches one semi-colon followed by zero or more whitespace characters.
  5. = - matches one equal sign.
  6. (xxxx) - forms a matching group.
  7. [^;]* - matches zero or more characters other than a semi-colon. This means it will match characters up to, but not including, a semi-colon or to the end of the string.
查看更多
梦该遗忘
7楼-- · 2018-12-31 11:01

Simple function for Get cookie with cookie name:

function getCookie(cn) {
    var name = cn+"=";
    var allCookie = decodeURIComponent(document.cookie).split(';');
    var cval = [];
    for(var i=0; i < allCookie.length; i++) {
        if (allCookie[i].trim().indexOf(name) == 0) {
            cval = allCookie[i].trim().split("=");
        }   
    }
    return (cval.length > 0) ? cval[1] : "";
}
查看更多
登录 后发表回答