Cover Image for Cookie with multiple Name
112 views

Cookie with multiple Name

To store multiple cookies with different names in JavaScript, you can set each cookie individually by specifying a unique name for each cookie. Here’s an example of setting multiple cookies:

JavaScript
document.cookie = "cookie1=value1; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
document.cookie = "cookie2=value2; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
document.cookie = "cookie3=value3; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";

In this example, three cookies are being set with the names cookie1, cookie2, and cookie3. Each cookie has a unique value and the same expiration date, path, and other attributes. You can modify the names, values, and attributes of each cookie as needed.

When retrieving or manipulating these cookies later, you can access them using their respective names. Here’s an example of retrieving the values of these cookies:

JavaScript<span role="button" tabindex="0" data-code="let cookie1Value = getCookieValue("cookie1"); let cookie2Value = getCookieValue("cookie2"); let cookie3Value = getCookieValue("cookie3"); function getCookieValue(cookieName) { let cookies = document.cookie.split("; "); for (let i = 0; i
let cookie1Value = getCookieValue("cookie1");
let cookie2Value = getCookieValue("cookie2");
let cookie3Value = getCookieValue("cookie3");

function getCookieValue(cookieName) {
  let cookies = document.cookie.split("; ");
  for (let i = 0; i < cookies.length; i++) {
    let cookie = cookies[i].split("=");
    if (cookie[0] === cookieName) {
      return cookie[1];
    }
  }
  return null;
}

In this example, the getCookieValue function is used to retrieve the value of a specific cookie by name. It splits the document.cookie string into individual cookies and checks if the name matches the desired cookie. If found, it returns the corresponding value. If not found, it returns null.

You can modify this code to suit your specific needs, such as setting additional cookie attributes or performing other operations with the cookies.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS