Home >Web Front-end >JS Tutorial >How to set cookies and delete cookies

How to set cookies and delete cookies

silencement
silencementOriginal
2020-02-27 16:50:072628browse

How to set cookies and delete cookies

Cookies run on the client, and you can use JS to set cookies.

First of all, you need to understand the structure of cookies a little bit. Simply put: cookies are based on key values. It is saved in the form of key=value. Each cookie is usually separated by ";".

JS setting cookie:

Assume that in page A, you want to save the value of the variable username ("jack") to the cookie, and the key value is name, then the corresponding JS code is:

document.cookie="name="+username;

Read cookie

 function getCookie(name){
      var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
      if(arr=document.cookie.match(reg))
      return unescape(arr[2]);
      else
      return null;
    }

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

Statement:
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