How do I set and read cookies in JavaScript?
Asked on Aug 17, 2024
Answer
In JavaScript, you can set and read cookies using the "document.cookie" property. Here's a simple example to demonstrate how to do this.
// Function to set a cookie
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
// Function to get a cookie
function getCookie(name) {
const nameEQ = name + "=";
const cookiesArray = document.cookie.split(';');
for (let i = 0; i < cookiesArray.length; i++) {
let cookie = cookiesArray[i].trim();
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
// Example usage
setCookie("username", "JohnDoe", 7); // Set a cookie
console.log(getCookie("username")); // Read the cookie
Additional Comment:
✅ Answered with JavaScript best practices.- The "setCookie" function creates a cookie with a specified name, value, and expiration in days.
- The "getCookie" function retrieves the value of a cookie by its name.
- Cookies are stored as a single string in "document.cookie", separated by semicolons.
- Always ensure cookies are set with a path to avoid unexpected behavior.
Recommended Links:
← Back to All Questions