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.

Note that when creating a cookie, you should always include an expiration date so that the cookie is automatically deleted after a certain period of time.

This is an example that includes an expiration date:

let date = new Date(); date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // expire in 7 days let expires = "expires=" + date.toUTCString(); 
document.cookie = "username=Olise;" + expires;

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.

Note that the expires variable is set to a string that specifies the expiration date in UTC format.

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:

let cookies = document.cookie.split(";"); 
for (let i = 0; I < cookies.length; i++) { let cookie = cookies[i].trim(); 
if (cookie.startsWith("username=")) { let value = cookie.substring("username=".length); 
console.log("Username: " + value); } }

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