SoFunction
Updated on 2025-04-07

JavaScript method to set, get, clear single and multi-value cookies

I won’t say much nonsense, I will just post code to you.

The specific code is as follows:

var CookieUtil = (function () {
   var Cookie = function () {
     // Get single-value cookies      = function(name) {
       var start = (encodeURIComponent(name)) ;
       var end = (';', start) ;
       if(end == -) {
         end = ;
       }
       return decodeURIComponent((start++,end));
     };
     // Set single-value cookies      = function(name, value, expires, path, domain, secure) {
       var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
       // Set the default expiration time to seven days       if(expires == undefined) {
         var date = new Date();
         (() + ****);
         expires = date ;
       }
       if(expires instanceof Date) {
         cookieText += "; expires=" + ();
       }
       if(path != undefined) {
         cookieText += "; path=" + path;
       }
       if(domain != undefined) {
         cookieText += "; domain" + domain;
       }
       if(secure != undefined) {
         cookieText += "; secure";
       }
        = cookieText;
     };
     // Clear single value cookies      = function(name, path, domain, secure) {
       (name, '', new Date(), path, domain, secure );
     };
     // Set multi-value cookies      = function(name, subCookies, expires, path, domain, secure) {
       var cookieText = ";" + encodeURIComponent(name) + "=",
       arr = new Array();
       for(var attr in subCookies) {
         ([encodeURIComponent(attr)] + ":" + encodeURIComponent(subCookies[attr]));
       } 
       (name, ('&'), expires, path, domain, secure);
     };
     // Get multi-value cookies      = function(name) {
       var obj = {};
       var arr = (name).split('&');
       for(var i = , len = ; i < len; i++) {
         var tmpArr = arr[i].split(':');
         obj[decodeURIComponent(tmpArr[])] = decodeURIComponent(tmpArr[]);
       }
       return obj;
     };
     // Get child cookies of multi-value cookies      = function(name, subname) {
       var obj = (name);
       return obj[subname];
     };
     // Clear the specified multi-value cookie      = function(name,path,domain,secure) {
       (name, '', new Date(), path, domain, secure);
     };
     // Clear child cookies of specified multi-value cookies      = function(name, subname,path, domain, secure) {
       var obj = (name);
       delete obj[subname];
       (name, obj, null, path, domain, secure);
     };
   };
   return new Cookie();
 })();

The above code is the method of setting, obtaining, and clearing single-valued and multi-valued cookies in JavaScript. If you have any unclear areas, please leave me a message.