Tags
Laravel
Asked 3 years ago
17 Jun 2021
Views 346
Rickie

Rickie posted

How do I create and read a value from cookie?

How do I create and read a value from cookie?
Phpworker

Phpworker
answered Apr 27 '23 00:00

You can create and read cookies in JavaScript using the document.cookie property. Here's an example of how to create a cookie with a name " myCookie " and a value "myValue", that expires in one day:



document.cookie = "myCookie=myValue; expires=Wed, 28 Apr 2023 00:00:00 UTC; path=/";

In this example, the cookie is created by setting the document.cookie property to a string that consists of the cookie name, followed by an equal sign and the cookie value. The expires attribute sets the cookie's expiration date, and the path attribute specifies the URL path for which the cookie is valid.

To read the value of a cookie, you can use the document.cookie property again. Here's an example of how to read the value of the "myCookie" cookie:



const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
  const cookie = cookies[i].trim();
  if (cookie.startsWith('myCookie=')) {
    const myCookieValue = cookie.substring('myCookie='.length);
    console.log(myCookieValue);
  }
}

In this example, the document.cookie property is split into an array of individual cookies. Then, each cookie is checked to see if it starts with the name "myCookie". If a matching cookie is found, the code extracts its value and logs it to the console.

Note that cookies are stored as strings and have a limited size, so it's important to encode any data you store in them properly to avoid data loss or security issues. Additionally, make sure to be mindful of any privacy implications of setting cookies, and only use them when necessary for your application.
Post Answer