I created a cookie using Newcookie() and I can access it thorough the browser as below. Now I need to read the cookie
function getCookieValue(cookieName) {
console.log("=====getCookieValue=======");
var name = cookieName + "=";
var cookies = document.cookie.split(';');
console.log("=====ALL cookies======="+cookies);
if (!cookies) {
return null;
}
console.log("=====cookies.length======="+cookies.length);
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
console.log("=====cookies======="+cookies[0]);
if (cookie.indexOf(name) == 0) {
return cookie.substring(name.length, cookie.length);
}
}
return null;
}
But by using that method I cant read the cookie. Please advice me on this. Thanks
Your function is almost perfect. You just need to change this line:
document.cookie.split(';');
You can examine the result in the console by running the above statement: you’ll get an Array with all the cookies but each one of them is preceeded by a whitespace. That’s why the comparison
if (cookie.indexOf(name) == 0)
doesn’t work like expected, because the expected substring doesn’t start at position 0 but at 1.
Therefore, you’ll want to split the list of cookies not by a single semicolon but by a semicolon and a whitespace. I’m not sure about all the browsers out there, so I think the safest way to do it is with a RegExp that checks for an optional whitespace:
document.cookie.split(/;\s?/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With