Reputation: 2151
I have a function that searches the cookies string for a specific cookie and returns its value but I don't understand why it keeps returning null when the cookie exists.
document.cookie = "userName=nameHere";
function getCookie() {
document.cookie.split(";").forEach(cookie => {
if (cookie.substring(0, cookie.indexOf("=")) == "userName") {
var name = cookie.substring(cookie.indexOf("=") + 1);
console.log(name);
return name;
}
})
return null;
}
>> getCookie()
//prints
nameHere
//returns
null
Upvotes: 1
Views: 749
Reputation: 5112
A few things to note here:
That said, here is a working function:
document.cookie = "userName=nameHere";
function getCookie(cName) {
const decodedCookie = decodeURIComponent(document.cookie) // deal with any special character
// returns the value of the first element in the provided array that satisfies the provided testing function
const cookie = decodedCookie.split(";").find(c => c.substring(0, c.indexOf("=")) == cName)
if (!cookie) return null // cookie not found, return
const value = cookie.substring(cookie.indexOf("=") + 1)
return value
}
console.log(getCookie('userName'))
Upvotes: 1
Reputation: 14904
If you take a closer look you will see that there are actually 2 functions.
`.forEach(cookie => {`
You actually returning name
in the arrow function
A solution could be to go with a for
loop instead of forEach
Upvotes: 3
Reputation: 1107
My guess is that:
var name = cookie.substring(cookie.indexOf("=") + 1);
doesn't actually assign a name. Try putting an Alert, after the name var or log the name to check the contents.
Upvotes: -2