To get and set cookies in JavaScript, you can use the document.cookie property. Here are some examples:
Setting a cookie
To set a cookie, you can simply assign a string with the cookie name, value, and optional attributes to the document.cookie property. Here's an example of how to set a cookie with a name "myCookie" and a value "myValue", that expires in one day:
document.cookie = "myCookie=myValue; expires=Wed, 28 Apr 2023 00:00:00 UTC; path=/ ";
In this example, the cookie is created by setting the document.cookie property to a string that consists of the cookie name, followed by an equal sign and the cookie value. The expires attribute sets the cookie's expiration date, and the path attribute specifies the URL path for which the cookie is valid.
Getting a cookie
To get a cookie, you can read the document.cookie property, which returns a string containing all cookies for the current domain. You can then parse the string to find the value of a specific cookie. Here's an example of how to get the value of a cookie with the name "myCookie":
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith('myCookie=')) {
const myCookieValue = cookie.substring('myCookie='.length);
console.log(myCookieValue);
}
}
In this example, the document.cookie property is split into an array of individual cookies. Then, each cookie is checked to see if it starts with the name "myCookie". If a matching cookie is found, the code extracts its value and logs it to the console.
Deleting a cookie
To delete a cookie, you can set its expiration date to a time in the past. Here's an example of how to delete a cookie with the name "myCookie":
document.cookie = "myCookie=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
In this example, the cookie is deleted by setting its value to an empty string and its expiration date to a time in the past. The path attribute should be set to the same value as when the cookie was created, to ensure that it's deleted from the correct path.