Get cookie by name

前端 未结 30 1833
野的像风
野的像风 2020-11-22 03:58

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

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 04:34

    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.

提交回复
热议问题