Categories
JavaScript Answers

How to check if a cookie exists or else set cookie to expire in 10 days with JavaScript?

Spread the love

Sometimes, we want to check if a cookie exists or else set cookie to expire in 10 days with JavaScript.

In this article, we’ll look at how to check if cookie a exists or else set cookie to expire in 10 days with JavaScript.

How to check if cookie a exists or else set cookie to expire in 10 days with JavaScript?

To check if a cookie exists or else set cookie to expire in 10 days with JavaScript, we can read and write the to the document.cookie property.

For instance, we write:

if (/(^|;)\s*visited=/.test(document.cookie)) {
  console.log("Hello again!");
} else {
  document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10;
  console.log("first visit");
}

We check if the cookie string has the visit key with /(^|;)\s*visited=/.test(document.cookie).

If it’s true, we log 'Hello again'.

Otherwise, we assign document.cookie to "visited=true; max-age=" + 60 * 60 * 24 * 10 to add a cookie with key visited that expires in 10 days.

Conclusion

To check if a cookie exists or else set cookie to expire in 10 days with JavaScript, we can read and write the to the document.cookie property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *