dimvcl
dimvcl

Reputation: 299

How to access a document cookie through Javascript?

I created a cookie with document.cookie and when I do an alert it returns

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

How can I access the last, cookieValue?

Upvotes: 2

Views: 1426

Answers (3)

try-catch-finally
try-catch-finally

Reputation: 7624

This answer gives three solutions.

Step by step solution

The key=value pairs are split into an array, then the pair is split at = to get the name. The function makes use of ECMA Script 5's reduce(). The resulting object memo is returned if it is no longer null. In this case reduce() is gracefully used as find() that returns an altered value.

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

Step by step with the option to get all cookies

The key=value pairs are split into an array, then the pair is split at = to get the name. The function makes use of ECMA Script 5's reduce() to transform the intermediate array into an object where key will be an attribute of that object.

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

Quick and dirty

Uses a dynamically created Regular Expression to extract the key=value pair's value, finally decodes the value.

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

Upvotes: 0

skube
skube

Reputation: 6175

I'm sure there's a more elegant way but you could convert to an array:

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

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

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

Upvotes: 1

VishnuNair
VishnuNair

Reputation: 121

Let's say you have created a cookie using, document.cookie = "I am a cookie!"; To read the cookie and store it in a variable, you can use, var x = document.cookie;

Upvotes: 1

Related Questions