如何通过Javascript访问文档cookie?

时间:2015-12-06 17:14:20

标签: javascript cookies

我使用document.cookie创建了一个Cookie,当我发出提醒时,它会返回

nav=Panel; cookieValue=Panel; test=1; nav=Panel; cookieValue=buyer;

如何访问最后一个cookieValue

3 个答案:

答案 0 :(得分:1)

假设您使用了创建了一个cookie,     document.cookie =“我是一个cookie!”; 要读取cookie并将其存储在变量中,您可以使用,      var x = document.cookie;

答案 1 :(得分:1)

我确信有一种更优雅的方式,但你可以转换为数组:

var cookie = "nav=Panel; cookieValue=Panel; test=1; nav=Panel; cookieValue=buyer; ";

var cookieArray = cookie.split('; ');

alert(cookieArray[cookieArray.length-2]);

答案 2 :(得分:0)

这个答案给出了三个解决方案。

逐步解决方案

key=value对拆分为数组,然后将该对拆分为=以获取名称。该功能使用ECMA Script 5' reduce()。如果结果对象memo不再是null,则会返回该对象。在这种情况下,reduce()优雅地用作 find(),返回更改后的值

function getCookie(name) {
    return document.cookie.split("; ").reduce(function(memo, token){
        var pair;
        if (memo) {
            // we've already a value, don't bother parsing further values
            return memo;
        }
        pair = token.split("=");
        if (pair[0] === name) {
            // return the decoded value as memoized value if the key matches
            return decodeURIComponent(pair[1]);
        }
    }, null);
}

逐步选择获取所有Cookie

key=value对拆分为数组,然后将该对拆分为=以获取名称。该函数利用ECMA Script 5的reduce()将中间数组转换为key将成为该对象属性的对象。

function getCookies() {
    return document.cookie.split("; ").reduce(function(cookies, token){
        // split key=value into array
        var pair = token.split("=");
        // assign value (1) as object's key with (0)
        cookies[pair[0]] = decodeURIComponent(pair[1]);
        // pass through the key-value store
        return cookies;
    }, { /* start with empty "cookies" object */ });
}

function getCookie(name) {
    return getCookies()[name];
}

又快又脏

使用动态创建的正则表达式来提取key=value对的值,最后解码该值。

function getCookie(name) {
    return decodeURIComponent(
        document.cookie.replace(
            new RegExp("^.*" + name + "=([^\\s;]+).*$"), "$1"));
}
相关问题