Skip to content Skip to sidebar Skip to footer

Get A Cookie Value (javascript)

so I am new to Javascript and I am attempting to get a cookie value to keep track of a test. I have six questions and when a question is finished I increment 'counter' up 1 value,

Solution 1:

You're not using indexOf correctly.

functiongetCookie(cookieName) {
    var name = cookieName + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if ((c.indexOf(name)) == 0) {
            alert("found");
            return c.substr(name.length);
        }

    }
    alert("not found");
    returnnull;
}

Solution 2:

If you convert the cookie to a key-value pair then it can be easier to access cookies that way. You can do this with the following:

const cookiesArray = document.cookie.split(";").map((cookie) => cookie.trim());
  const cookiesHashmap = cookiesArray.reduce((all, cookie) => {
    const [cookieName, value] = cookie.split("=");
    return {
      [cookieName]: value,
      ...all,
    };
  }, {});

Post a Comment for "Get A Cookie Value (javascript)"