To delete a cookie in JavaScript, we can set its expiration date to a time in the past.
function deleteCookie(name, path, domain) { // Set the expiration date to a past time document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=" + path + "; domain=" + domain; } // Example usage: deleteCookie('username', '/home', 'example.com');
The deleteCookie function takes the cookie name, path, and domain as parameters.
It sets the document.cookie property with the same cookie name, an expiration date in the past (Thu, 01 Jan 1970 00:00:00 UTC), and the specified path and domain.
We can modify the "deleteCookie" function according to our needs, depending on whether the cookies are set with additional attributes such as secure, HttpOnly, or others.
Make sure to include those attributes in the deletion process if they were present when the cookie was set.
function deleteCookie(name) { document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; } // Example usage: deleteCookie('username');
the path=/ ensures that the deletion operation applies to the root path of the domain.