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 the string indexOf
method.
For instance, we write
const index = document.cookie.indexOf("cookie_name=");
to call document.cookie.indexOf
with "cookie_name="
to check if the cookie with key cookie_name
exists.
If it exists, then indexOf
returns an starting index of the item, which should be larger than -1.
COnclusion
To check if a cookie exists with JavaScript, we can use the string indexOf
method.