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

当前回答

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

我喜欢使用闭包按名称获取cookie值。下面的闭包将允许您通过名称获取cookie值,但只有在更新了cookie字符串时才会解析cookie字符串。

您可以通过以下方法检索cookie的值:

var foo = cookies.get( "bar" );

代码:

var cookies = ( function() {
    var cookieString = null;
    var cookieArray = [];

    function getValOf( name ) {
        if ( newCookies() ) {
            parseCookieString()
        }
        return cookieArray[ name ];
    }

    // Check if new cookies have been added
    function newCookies() {
        return cookieString === document.cookie;
    }

    function parseCookieString() {
        cookieString = document.cookie;

        // Separate cookies
        var cookies = cookieString.split( ";" );

        // Empty previous cookies
        cookieArray = [];

        // Update cookieArray with new name-value pairs
        for ( var i in cookies ) {

            // Separate name and value
            var nameVal = cookies[ i ].split( "=" );
            var name = nameVal[ 0 ].trim();
            var value = nameVal[ 1 ].trim();

            // Add cookie name value pair to dictionary
            cookieArray[ name ] = value;
        }
    }

    return {

        /**
         * Returns value or undefined
         */
        get: function( name ) {
            return getValOf( name );
        }  
    };
})();
function GetCookieValue(name) {
    var found = document.cookie.split(';').filter(c => c.trim().split("=")[0] === name);
    return found.length > 0 ? found[0].split("=")[1] : null;
}

一个简单的方法:)

const cookieObj = new URLSearchParams(document.cookie.replaceAll("&", "%26").replaceAll("; ","&"))
cookieObj.get("your-cookie-name")

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

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