Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

A Function to Set a Cookie

First, we define a function that saves the visitor’s name in a cookie.

Example

function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  let expires = “expires=”+ d.toUTCString();
  document.cookie = cname + “=” + cvalue + “;” + expires + “;path=/”;
}

Explanation of the example:

The function above takes three parameters: the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).

The function creates the cookie by combining the cookie name, cookie value, and the expiration string.

A Function to get cookie

Next, we define a function that retrieves the value of a specified cookie.

Example

function getCookie(cname) {
  let name = cname + “=”;
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(‘;’);
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ‘ ‘) {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return “”;
}

Explanation of the function:

  1. The function takes the cname (cookie name) as a parameter.
  2. It creates a variable name that holds the search text (cname + "=").
  3. The cookie string is decoded to properly handle special characters, such as ‘$’.
  4. The document.cookie is split by semicolons into an array (ca = decodedCookie.split(';')).
  5. The function loops through the ca array (for (i = 0; i < ca.length; i++)) and checks each value (c = ca[i]).
  6. If the cookie is found (c.indexOf(name) == 0), it returns the cookie’s value (c.substring(name.length, c.length)).
  7. If the cookie is not found, it returns an empty string ("").