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

How Do I Create and Read Cookies in JavaScript?

Linda Hamilton
Release: 2024-12-20 01:06:09
Original
828 people have browsed it

How Do I Create and Read Cookies in JavaScript?

Creating and Reading Cookies in JavaScript

Cookies are small text files that websites use to store information on users' devices. In JavaScript, there are several functions you can use to work with cookies.

Creating a Cookie

To create a cookie, use the createCookie function. This function takes three parameters:

  • name: The name of the cookie.
  • value: The value to store in the cookie.
  • days: The number of days the cookie should expire in (optional).

Example:

createCookie("user_name", "John Doe", 30);
Copy after login

Reading a Cookie

To read a cookie, use the getCookie function. This function takes one parameter:

  • c_name: The name of the cookie to retrieve.

Example:

var username = getCookie("user_name");
Copy after login

The above code assigns the value of the "user_name" cookie to the username variable. If the cookie does not exist, the username variable will be an empty string.

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

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