Home > Web Front-end > JS Tutorial > How to delete cookies in javascript

How to delete cookies in javascript

醉折花枝作酒筹
Release: 2023-01-05 16:07:34
Original
5094 people have browsed it

If you want to delete cookies in javascript, you first need to find the value corresponding to the name of the cookie and set it to expire; then set the value of the expire attribute to the expiration date (that is, any past date). Browse The server will automatically delete cookie files.

How to delete cookies in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

I always thought that by setting the document.cookie object of javascript, I can simply set and delete the cookie value on the browser side. Many articles on the Internet also teach this, but recently I found that it is easy to set the document.cookie of javascript. The value of does not completely delete or change the cookie.

To use JavaScript to clear cookies, you must first find the value corresponding to the Name of the cookie, and then set it to expire:
The following methods are used to find the cookie:

function getCookie2(name){
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));  
    if(arr != null) 
        return unescape(arr[2]); 
        return null;
}
Copy after login

After finding it, set it to expire. Remember to set domain and path. Only if these two parameters are exactly the same as the parameters you want to delete can you delete it.

function resetNfluent(){
		alert("before=>"+document.cookie);
		var exp  = new Date();
		exp.setTime(exp.getTime() - 1);
		var cval=getCookie2('name');
		var lanObj=document.getElementById('lanOption');
		var lanSel=lanObj.value;
		alert(lanSel);
		if(lanSel=='en'){
			alert('let\'s reset nFluent');
			alert('cval=>'+cval);
			if(cval!=null){
				document.cookie="name="+cval+";
				domain=.example.com;
				expires="+exp.toGMTString()+";
				path=/";
			}else{
				document.cookie="name=;
				domain=.example.com;
				expires="+exp.toGMTString()+";
				path=/";
				}
		}else{
			alert('Don\'t need reset nFluent');
			}
		alert("after=>"+document.cookie);
    }
Copy after login

Recommended learning: javascript video tutorial

The above is the detailed content of How to delete cookies in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template