Home >Web Front-end >JS Tutorial >How Do I Create and Read Cookies Using JavaScript?
Creating and Reading Cookies with JavaScript
In JavaScript, you can manage cookies through functions specifically designed for this purpose.
Creating a Cookie:
The createCookie function allows you to establish a cookie:
function createCookie(name, value, days) { // Calculate expiration date if provided var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } // Create the cookie document.cookie = name + "=" + value + expires + "; path=/"; }
Reading a Cookie:
The getCookie function retrieves the value of an existing cookie:
function getCookie(c_name) { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cr = cookies[i].split('='); if (cr[0].trim() == c_name) { return unescape(cr[1]); } } return ""; }
The above is the detailed content of How Do I Create and Read Cookies Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!