What's a good way to check if a cookie exist?
Conditions:
Cookie exists if
cookie1=;cookie1=345534; //or cookie1=345534;cookie1=; //or cookie1=345534;
Cookie doesn't exist if
cookie=; //or <blank>
document. cookie. indexOf('cookie_name='); It will return -1 if that cookie does not exist.
Right-click anywhere on a web page, on the website where you want to check the cookie expiration date. Then, open up the developer tools by selecting Inspect or Inspect element, depending on the browser.
Delete a Cookie with JavaScript Just set the expires parameter to a past date: document. cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.
You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.
function getCookie(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin != 0) return null; } else { begin += 2; var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } } // because unescape has been deprecated, replaced with decodeURI //return unescape(dc.substring(begin + prefix.length, end)); return decodeURI(dc.substring(begin + prefix.length, end)); } function doSomething() { var myCookie = getCookie("MyCookie"); if (myCookie == null) { // do cookie doesn't exist stuff; } else { // do cookie exists stuff } }
I have crafted an alternative non-jQuery version:
document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)
It only tests for cookie existence. A more complicated version can also return cookie value:
value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
Put your cookie name in in place of MyCookie
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With