kiran
answered Apr 24 '23 00:00
Cookies are small files that a website stores on a user's computer to remember their preferences or track their activity. JavaScript can be used to manage cookies, including creating, reading, and deleting them.
To create a cookie using JavaScript, you can use the document.cookie property. For example, you might create a cookie named "username" with the value "John Doe", along with an expiration date and a path for the cookie:
document.cookie = "username=John Doe; expires=Thu, 01 Jan 2026 00:00:00 UTC; path=/";
To read a cookie using JavaScript, you can use the document.cookie property to retrieve a string containing all the cookies associated with the current page. You can then parse the string to find a specific cookie. For example, you might search for the "username" cookie:
let cookies = document.cookie.split("; ");
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].split("=");
if (cookie[0] === "username") {
console.log("The username is " + cookie[1]);
}
}
To delete a cookie using JavaScript, you can set its value to an empty string and set an expiration date in the past. For example, you might delete the "username" cookie like this:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
I hope that helps!