js delete cookie code example
Example 1: clear cookies js
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
deleteAllCookies();
Example 2: javascript delete cookie
function deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Example 3: javascript create cookie
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
setCookie("user_email","[email protected]",30);
var userEmail=getCookie("user_email");
Example 4: how to delete a cookie in js
document.cookie = "cookiename= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"
Example 5: delete cookies by domain javascript
document.cookie = 'my_cookie=; path=/; domain=.example.com; expires=' + new Date(0).toUTCString();
Example 6: clearing cookie in js
document.cookie.split(";")
.forEach(function(c) {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });