Deleting a Cookie in JavaScript


Deleting a Cookie in JavaScript

The numerous techniques to set and update a cookie in JavaScript were covered in the preceding section. Apart from that, we may remove a cookie using JavaScript. We can see all of the options for deleting a cookie here.

Different ways to delete a Cookie

  • The following are the methods for deleting cookies: A cookie can be removed by utilising the expire attribute.
  • The max-age property can also be used to remove a cookie.
  • Using a web browser, we may remove a cookie explicitly.
Delete Cookies

You may remove a cookie by changing its expiration date to any point in the past and giving it an empty value.

Here's how we'd go about deleting the userId cookie from earlier

Example

Example :

<!DOCTYPE html> <html lang="en-US"> <head> <script> function setCookie(cname,cvalue,exdays) { const d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); let expires = "expires=" + d.toGMTString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(';'); for(let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function checkCookie() { let user = getCookie("username"); if (user != "") { alert("Welcome again " + user); } else { user = prompt("Please enter your name:",""); if (user != "" && user != null) { setCookie("username", user, 30); } } } document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Delete </script> </head> <body onload="checkCookie()"></body> </html>

OUTPUT:

(reload page for output)