This is the script that i am using to fetch a particular cookie lastvisit :
AFTER THE EDIT
// This document writes a cookie
// called from index.php
window.onload = makeLastVisitCookie;
function makeLastVisitCookie() {
var now = new Date();
var last = new Date();
now.setFullYear(2020);
// set the cookie
document.cookie = "lastvisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();
var allCookies = document.cookie.split(";");
for( var i=0 ; i < allCookies.length ; i++ ) {
if(allCookies[i].split("=")[0]== "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited this site on" + allCookies[i].split("=")[1];
} else {
alert("testing..testing..");
}
}
}
From this script the if part never works though there are 5 cookies stored from my website. (including the cookie that i am saving from this script) What is the mistake that i am making while fetching the cookie named lastvisit ?
You’re splitting the cookie by
;an comparing those tokens withlastvisit. You need to split such a token by=first.allCookies[i]looks likekey=valand will never equallastvisit. Een ifallCookies[i] == "lastvisit"is true, the result will still not be as expected since you’re showing the value ofallCookies[i + 1]which would bethis=the_cookie_after_lastvisit.if(allCookies[i].split("=") == "lastvisit") {should be:"You visited this site on" + allCookies[i+1];should be:The
2argument ofsplitmakes cookies likesum=1+1=2be read correctly. When splitting cookies by;, the key may contain a leading space which much be removed before comparing. (/^ +/is a regular expression where^matches the beginning of a string and+one or more spaces.)Alternatively, compare it directly against a RE for matching the optional spaces as well (
*matches zero or more occurences of a space character,$matches the end of a string):I’ve tested several ways to get a cookie including using regular expressions and the below was the most correct one with best performance: