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?
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?
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;
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]);
This answer gives three solutions.
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);
}
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];
}
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"));
}