Syntax
The syntax for creating and saving cookie is as follows:
The cookie saves the data in key-value pairs.
Creating a Cookie
You can create a cookie by assigning a string to the document.cookie, for example, userName.
Getting a Cookie
Now, if we want to have a look at the Cookie, we can get the cookie by assigning document.cookie to a variable and then console it.
console.log(cookie.Stat);
Setting/Updating a Cookie
We can update a cookie as well using the same syntax we used for creating a cookie. To add the expiry date in the cookie, for example, we will use the following technique:
expiryDate.setDate(expiryDate.getDate() + 1)
expiryDate.toUTCString()
document.cookie = "userName=John"
document.cookie = "expires=" + expiryDate.toUTCString()
After updating, take a look at the cookie:
You can see that cookie is updated.
Deleting a Cookie
There is no built-in method or object for deleting a cookie in Python, but a cookie is deleted when it expires. By assigning a past date to a cookie, you can delete it.
expiryDate.setDate(expiryDate.getDate() - 1)
expiryDate.toUTCString()
document.cookie = "userName=John"
document.cookie = "expires=" + expiryDate.toUTCString()
After assigning a past date, the cookie will no longer work and will self-delete by expiring.
Conclusion
So, this is how you can create a cookie, set or update a cookie, and delete a cookie in JavaScript. In this article, you learned about cookie usage in JavaScript, including how cookies can help you in development and save necessary user data. You can continue to learn more about JavaScript at linuxhint.com. Thank you!
from Linux Hint https://ift.tt/352pRQM
0 Comments