JS sets the method to get cookies

  • 2020-03-30 01:28:14
  • OfStack

In combination with the JavaScript authority guide and the information collected on the Internet during the development of the project, two methods of setting and obtaining cookies are summarized.


<script>
//Cookie  Settings; Methods a
function setCookie(name,value){ 
  var exp = new Date(); 
  exp.setTime(exp.getTime() + 1*60*60*1000);//Valid for 1 hour
  document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
}

//Cookie setting method 2 stores cookies directly
document.cookie = "homepage = //www.jb51.net";
 
//Take the cookie function method one
function getCookie(name){
  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
  if(arr != null)    
    return unescape(arr[2]);
  return null;
}
//Cookies & cake; Method 2
function getCookie(key){
  if(key==null)
    return null;
  if(Object.prototype.toString.call(key)=='[object String]'|| Object.prototype.toString.call(key)=='[object Number]')
  {
    var arrStr = document.cookie.split(";");
    for(var i= 0;i<arrStr.length;i++){
    var temp = arrStr[i].split("=");
    if(temp[0]==key)
      return unescape(temp[1]);
    }
    return null;
  }
  return null;
}
</script>

When learning a lot of js methods will not meet on the Internet to find information, until master.


Related articles: