2

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?

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
dimvcl
  • 289
  • 1
  • 3
  • 13
  • 2
    Possible duplicate of [How do I create and read a value from cookie?](http://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie) – Touffy Dec 06 '15 at 17:15
  • https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie – epascarello Dec 06 '15 at 18:10

3 Answers3

1

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;

VishnuNair
  • 121
  • 4
  • 12
1

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]);
skube
  • 5,867
  • 9
  • 53
  • 77
0

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"));
}
try-catch-finally
  • 7,436
  • 6
  • 46
  • 67