JS save and delete cookie operation to determine whether the cookie exists

  • 2020-03-29 23:45:22
  • OfStack

Sometimes we need to use cookie to save the user name and record the login status. How to correctly determine whether the cookie of this user exists? You can't simply use a! = ".

 if(c_start == -1){

The correct method is: to determine whether there is a cookie named username3, use document.cookie.indexof (" username3= ") to determine, if the return value is -1, it does not exist.

JS save and delete cookie operation

Js save, delete cookie operation is more convenient, do not need to write in the program, it is easy to change, more complete js save, delete cookie operation method is as follows:

<script language=javascript> 
 //Get the value of coolie
function cookie(name){    
   var cookieArray=document.cookie.split("; "); //Gets the split cookie name-value pair & NBSP;    
   var cookie=new Object();    
   for (var i=0;i<cookieArray.length;i++){    
      var arr=cookieArray[i].split("=");       //Separating name from value & NBSP;    
      if(arr[0]==name)return unescape(arr[1]); //If the cookie is specified, returns its value & NBSP;    
   return ""; 

function delCookie(name)//Delete the cookie
   document.cookie = name+"=;expires="+(new Date(0)).toGMTString();

function getCookie(objName){//Gets the value of the cookie with the specified name
    var arrStr = document.cookie.split("; ");
    for(var i = 0;i < arrStr.length;i ++){
        var temp = arrStr[i].split("=");
        if(temp[0] == objName) return unescape(temp[1]);

function addCookie(objName,objValue,objHours){      //Add a cookie
    var str = objName + "=" + escape(objValue);
    if(objHours > 0){                               //The cookie will disappear when the browser is closed
        var date = new Date();
        var ms = objHours*3600*1000;
        date.setTime(date.getTime() + ms);
        str += "; expires=" + date.toGMTString();
   document.cookie = str;

function SetCookie(name,value)//Two parameters, the name of the cookie and the value
    var Days = 30; //This cookie will be stored for 30 days
    var exp = new Date();    //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();

function getCookie(name)//Cookies & cake;            
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
    if(arr != null) return unescape(arr[2]); return null;

function delCookie(name)//Delete the cookie
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();

Related articles: