js clear all cookies

Time:2022-11-25

I tried a lot of codes written on the Internet to clear the cookie. The logic is to set the cookie validity period to the expiration time, but it has no effect. Finally, I found that I need to add max-age=0

const clearCookie = () => {
  var keys = document.cookie.match(/[^ =;]+(?==)/g);
  if (keys) {
    for (var i = keys.length; i--; ) {
      document.cookie =
        keys[i] +
        "=0;expires=" +
        new Date(0).toUTCString() +
        ";max-age=0";
    }
  }
};