In JavaScript, cookies are small pieces of data stored on the client-side (in the user's browser). They are commonly used to store information about the user or their preferences. Here's how you can work with cookies in JavaScript:
Setting a Cookie:
You can set a cookie using the document.cookie property. Here's an example:
// Function to set a cookie
function setCookie(name, value, daysToExpire) {
var expires = "";
if (daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
// Example: Set a cookie named "username" with value "John" that expires in 7 days
setCookie("username", "John", 7);
Reading a Cookie:
To read a cookie, you can use the document.cookie property or create a function to get a specific cookie value by name (as shown in the previous response):
// Function to get a specific cookie value by name
function getCookie(name) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.startsWith(name + '=')) {
return cookie.substring(name.length + 1);
}
}
return null;
}
// Example: Read the value of the "username" cookie
var usernameValue = getCookie('username');
console.log('Username:', usernameValue);
Deleting a Cookie:
To delete a cookie, you can set its expiration date to a date in the past:
// Function to delete a cookie by name
function deleteCookie(name) {
setCookie(name, "", -1);
}
// Example: Delete the "username" cookie
deleteCookie('username');
Remember that cookies are limited in size and are sent with every HTTP request, so it's important to use them judiciously and consider other storage options (like Local Storage or Session Storage) for larger amounts of data.
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In JavaScript, cookies are small pieces of data stored on the client-side (in the user's browser). They are commonly used to store information about the user or their preferences. Here's how you can work with cookies in JavaScript:
Setting a Cookie:
You can set a cookie using the document.cookie property. Here's an example:
Reading a Cookie:
To read a cookie, you can use the document.cookie property or create a function to get a specific cookie value by name (as shown in the previous response):
Deleting a Cookie:
To delete a cookie, you can set its expiration date to a date in the past:
Remember that cookies are limited in size and are sent with every HTTP request, so it's important to use them judiciously and consider other storage options (like Local Storage or Session Storage) for larger amounts of data.