Javascript Cookies
Cookies are little text files that a website stores on a user's device in JavaScript. They are frequently used to keep data like user preferences, login information, and the items of purchasing carts. Here's an illustration of how to make a cookie in JavaScript:
document.cookie
=
"username=Olise";
In this example, you will set a cookie named username with the value of Olise. The document.cookie
property is used to access the cookie functionality in JavaScript.
This is an example that includes an expiration date:
In this example, you will set a cookie named username with the value of Olise and an expiration date of 7 days from the current time.
To read a cookie in JavaScript, you can use the document.cookie
property to access the entire cookie string, and then parse it to extract the value of a specific cookie.
Example:
In this example, you will use the split() method to split the document.cookie
string into an array of individual cookies. We then loop through the array, and for each cookie, we trim any whitespace and check if it starts with the name of the cookie we're interested in (in this case, username). If you find a match, you extract the value of the cookie using the substring() method and print it to the console using console.log().
Last updated