Categories
JavaScript Answers

How to check if a cookie exists with JavaScript?

Spread the love

Sometimes, we want to check if a cookie exists with JavaScript.

In this article, we’ll look at how to check if a cookie exists with JavaScript.

How to check if a cookie exists with JavaScript?

To check if a cookie exists with JavaScript, we can use a regex.

For instance, we write

document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/);

to call match with a regex to look for the cookie with key MyCookie.

We make sure we’re looking for substring between a semicolon and with = after the key with (.*;)?\s and \s*[^;]+(.*)?.

document.cookie is a string with all the cookies.

Conclusion

To check if a cookie exists with JavaScript, we can use a regex.

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 *