Home >Web Front-end >JS Tutorial >How to Delete a Cookie in JavaScript?

How to Delete a Cookie in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 00:18:09979browse

How to Delete a Cookie in JavaScript?

Deleting Cookies in JavaScript

Creating cookies is often a necessary task for web development. However, deleting cookies can also be essential to maintain user privacy or control data usage. This question focuses on how to delete a cookie in JavaScript.

Correctness of Cookie Creation Function
The provided createCookie function appears correct for creating a cookie. It sets the name, value, and expiration date as parameters.

Deleting a Cookie
To delete a cookie at the beginning of a program, the recommended approach is to use the delete_cookie function. Here's how it works:

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";
  }
}

This function takes three optional parameters: name, path, and domain. It checks if the cookie with the specified name exists using the get_cookie function defined below:

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

If the cookie exists, the delete_cookie function sets the cookie expiration date to a date in the past (January 1, 1970), effectively deleting it. By using optional parameters, the function supports deleting a cookie from a specific path or domain.

The above is the detailed content of How to Delete a Cookie in 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