JavaScript cookies are small data files that a web server stores on a user's computer. They can be used to store data like user preferences, login details, and goods from shopping carts. In this article, we'll examine JavaScript cookies in more detail and give several usage examples.
Cookie Creation:
The document.cookie attribute in JavaScript can be used to create cookies. The following is the syntax for creating a cookie:
document.cookie = "cookieName=cookieValue; expires=cookieExpiryDate;
path=cookiePath";
cookieName: The name of the cookie you want to create.
cookieValue: The value you want to assign to the cookie.
cookieExpiryDate: The cookie's expiration date and time (optional).
cookiePath: The cookie's availability path (optional).
Let's take the example of wanting to build a cookie to remember a user's name. To accomplish this, set "username" as the cookieName and "username" as the cookieValue:
document.cookie = "username=Elyas";
Reading a Cookie:
The document.cookie property can be used to read a cookie in JavaScript. The cookie property of the document returns a string containing all of the cookies for the current document. This text can then be parsed to find the value of a specific cookie.
Assume you want to get the value of the "username" cookie we created earlier. This can be accomplished as follows:
let cookies = document.cookie.split(';');
for(let i=0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
if (cookie.startsWith("username=")) {
let username = cookie.substring("username=".length, cookie.length);
console.log("Username is " + username);
}
}
In this code, we use semicolons to separate the document.cookie string into individual cookies. Then we loop through each cookie and see if it begins with "username=". If it does, we extract the cookie value and log it to the console.
Deleting a Cookie:
To delete a cookie in JavaScript, change the cookie's expiry date to a date in the past. This will result in the cookie being erased.
Assume you want to get rid of the "username" cookie. You can accomplish this by doing the following:
document.cookie = "username=;
expires=Thu, 01 Jan 1990 00:00:00 UTC; path=/;";
We set the "username" cookie's value to an empty string, set the expiration date to a date in the past, and set the path to "/" to ensure that the cookie is erased from all pathways.
Conclusion:
JavaScript cookies are a valuable resource for web developers. They can be used to save user information, preferences, and goods from the shopping cart. Cookies allow you to deliver a personalized experience for your users while also improving the functionality of your website. In this blog, we demonstrated how cookies may be generated, read, and removed in JavaScript.
Top comments (0)