Home >Web Front-end >JS Tutorial >How Can I Delete a Cookie Using JavaScript?

How Can I Delete a Cookie Using JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 22:53:09185browse

How Can I Delete a Cookie Using JavaScript?

Deleting Cookies with JavaScript

In your code, you've created a function called setCookie to set the cookie_name with the provided value. While your createCookie function is defined, it's not utilized in your code.

To remove the cookie effectively, consider incorporating the following approach:

function delete_cookie(name, path, domain) {
  if (get_cookie(name)) {
    document.cookie =
      name +
      "=" +
      ((path) ? ";path=" + path : "") +
      ((domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

You can define the get_cookie function as follows:

function get_cookie(name) {
  return document.cookie.split(";").some((c) => {
    return c.trim().startsWith(name + "=");
  });
}

By using the delete_cookie function at the start of your program, you can effectively remove the specified cookie by setting its expiration date to a past time.

The above is the detailed content of How Can I Delete a Cookie Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn