Home >Web Front-end >JS Tutorial >How Do I Create and Read Cookies Using JavaScript?

How Do I Create and Read Cookies Using JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 12:35:25343browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn