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

How Do I Create and Retrieve Cookies Using JavaScript?

Mary-Kate Olsen
Release: 2024-12-22 00:36:03
Original
1037 people have browsed it

How Do I Create and Retrieve Cookies Using JavaScript?

Creation and Retrieval of Cookies in JavaScript

Cookies are a mechanism for storing key-value pairs in a browser's memory. They are commonly used to maintain session information, user preferences, and other data that needs to persist between page refreshes.

In JavaScript, the process of creating and retrieving cookies is straightforward.

Creating a Cookie:

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}
Copy after login

Retrieving a Cookie:

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
Copy after login

To use these functions, simply pass in the desired cookie name, value, and expiry duration (in days) to createCookie(). To retrieve a cookie, pass in its name to getCookie().

The above is the detailed content of How Do I Create and Retrieve Cookies Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template