Tips for creating cookies and reading cookie_javascript using javascript

Source: Internet
Author: User
This article mainly introduces how to create and read cookies in javascript. The content is easy to learn. Interested friends can refer to the content in this article, describes how to create a cookie in javascript and how to read a cookie in javascript. The details are as follows:

1. Create a Cookie

Document. cookie = 'key = value ';

Special characters are encoded using encodeURIComponent ().

Document. cookie = 'user = '+ encodeURIComponent ('Guo Qian ;');

Use decodeURIComponent () for reading ()

For example:

Document. cookie = 'name = guoqian '; document. cookie = 'Age = 24'; document. cookie = 'address = hunanc'; document. cookie = 'user = '+ encodeURIComponent ('Guo Qian ;');

Customize a cookie Creation Method

function SetCookie(name, value, expires, path, domain, secure) { var today = new Date(); today.setTime(today.getTime()); if(expires) { expires *= 86400000; } var expires_date = new Date(today.getTime() + (expires)); document.cookie = name + "=" + escape(value)  + (expires ? ";expires=" + expires_date.toGMTString() : "")  + (path ? ";path=" + path : "")  + (domain ? ";domain=" + domain : "")  + (secure ? ";secure" : "");}

Ii. obtain cookies

Use string

function getCookieByString(cookieName){ var start = document.cookie.indexOf(cookieName+'='); if (start == -1) return false; start = start+cookieName.length+1; var end = document.cookie.indexOf(';', start); if (end == -1) end=document.cookie.length; return document.cookie.substring(start, end);}

Array

Function getCookieByArray (name) {var cookies = document. cookie. split (';'); var c; for (var I = 0; I
 
  

The above is all the content of this article, hoping to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.