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.