JS/jquery operation cookie [ORIGINAL + conversion]

Source: Internet
Author: User
Tags set cookie setcookie

Update:

I used the following content before. In fact, I used these two methods in my project.

// Obtain the cookie value function getcookie (name) {var arr = document. cookie. match (New Regexp ("(^ |; \ s *)" + name + "= ([^;] *) (; | $ )")); // I tested this regular expression for a long time and it should be okay. The following explains if (Arr! = NULL) return Unescape (decodeuri (ARR [2]); Return "" ;}// set cookiefunction setcookie (c_name, value, expiredays) {var exdate = new date (); exdate. setdate (exdate. getdate () + expiredays); document. cookie = c_name + "=" + escape (value) + (expiredays = NULL )? "": "; Expires =" + exdate. toutcstring ());}

Regular Expressions in getcookie:

For example, if we are looking for the cookie member_id, the name is member_id, and the above regular expressions determine three situations:

Starting with member_id, member_id is in the middle of the cookie string, and member_id is at the end of the string.

So what we need to match is name + "= ([^;] *) and put the value in the group. This segment can start from name matching.

When does the match end? (; | $) indicates the first semicolon after the name is matched. If the position is the last segment, no semicolon exists, but it's already the end ($ ).

When does it start? Similarly, (^ |; \ s *), it either starts with a semicolon or a space, to separate the previous attribute. This is the principle of this regular expression.

 

Sample COOKIE:

"_ Utma = 159719458.1137661975.1293897187.1295114244.1295271343.12;

_ Utmz = 159719458.1293897187.1.1.utmcsr = (direct) | utmccn = (direct) | utmcmd = (none );
Member_mail = ***** % 40qq.com;
Member_nickname = % E5 % 85% 9C % E5 % 85% 9C % E6 % B2 % a1 % E9 % 92% B1; group_id = 0;
Join_time = 1293696797; sitemsg = true; member_id = 37;
PHPSESSID = lb2ecoespc8asm1ht0stqb43b7"

Use the above regular expression to obtain the following array:

[

"; Member_id = 37 ;",

";",

"37 ",

";"

]

The first element is the maximum matching, and then it is in the brackets in sequence. In this way, except for the maximum matching, the first bracket is the value in the second bracket.


======== The following are others,

Full text reprint, backup, original see: http://www.cnblogs.com/qiantuwuliang/archive/2009/07/19/1526663.html

 

Jquery cookie is a good cookie plug-in. The general usage is as follows:
Example $. Cookie ('name', 'value ');
Set the cookie value and set the value of the name variable to value.
Example $. Cookie ('name', 'value', {expires: 7, path: '/', domain: 'jquery. com', secure: true });
Create a cookie, including the Domain Name of the validity period.
Example $. Cookie ('name', 'value ');
Create cookie
Example $. Cookie ('name', null );
Delete a cookie

VaR account = $. Cookie ('name ');
Get a cookie (name) value to myvar

The Code is as follows:

jQuery.cookie = function(name, value, options) {    if (typeof value != 'undefined') { // name and value given, set cookie        options = options || {};        if (value === null) {            value = '';            options.expires = -1;        }        var expires = '';        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {            var date;            if (typeof options.expires == 'number') {                date = new Date();                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));            } else {                date = options.expires;            }            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE        }        var path = options.path ? '; path=' + options.path : '';        var domain = options.domain ? '; domain=' + options.domain : '';        var secure = options.secure ? '; secure' : '';        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');    } else { // only name given, get cookie        var cookieValue = null;        if (document.cookie && document.cookie != '') {            var cookies = document.cookie.split(';');            for (var i = 0; i < cookies.length; i++) {                var cookie = jQuery.trim(cookies[i]);                // Does this cookie string begin with the name we want?                if (cookie.substring(0, name.length + 1) == (name + '=')) {                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));                    break;                }            }        }        return cookieValue;    }};

Then I read the discuz! Cookie Operation Method
As follows, it is found that the traversal is missing; the processing of the split Array

function getcookie(name) {var cookie_start = document.cookie.indexOf(name);var cookie_end = document.cookie.indexOf(";", cookie_start);return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));}function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {var expires = new Date();expires.setTime(expires.getTime() + seconds);document.cookie = escape(cookieName) + '=' + escape(cookieValue)+ (expires ? '; expires=' + expires.toGMTString() : '')+ (path ? '; path=' + path : '/')+ (domain ? '; domain=' + domain : '')+ (secure ? '; secure' : '');}

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.