1 String. Prototype. Trim = Function ()
2 {
3 Return This . Replace ( / ^ \ S + / G, "" ). Replace ( / \ S + $ / G, "" );
4 }
5
6 Function Jscookie ()
7 {
8 This . Getcookie = Function (Key)
9 {
10 VaR Cookie = Document. Cookie;
11 VaR Cookiearray = Cookie. Split ( ' ; ' );
12 VaR Getvalue = "" ;
13 For ( VaR I = 0 ; I < Cookiearray. length; I ++ )
14 {
15
16 If (Cookiearray [I]. Trim (). substr ( 0 , Key. length) = Key)
17 {
18 Getvalue = Cookiearray [I]. Trim (). substr (key. Length + 1 );
19 Break ;
20 }
21 }
22
23 Return Getvalue;
24 };
25 This . Getchild = Function (Cookiekey, childkey)
26 {
27 VaR Child = This . Getcookie (cookiekey );
28 VaR Childs = Child. Split ( ' & ' );
29 VaR Getvalue = "" ;
30
31 For ( VaR I = 0 ; I < Childs. length; I ++ )
32 {
33 If (Childs [I]. Trim (). substr ( 0 , Childkey. length) = Childkey)
34 {
35 Getvalue = Childs [I]. Trim (). substr (childkey. Length + 1 );
36 Break ;
37 }
38 }
39 Return Getvalue;
40 };
41 This . Setcookie = Function (Key, value, expire, domain, PATH)
42 {
43 VaR Cookie = "" ;
44 If (Key ! = Null && Value ! = Null )
45 Cookie + = Key + " = " + Value + " ; " ;
46 If (Expire ! = Null )
47 Cookie + = " Expires = " + Expire. togmtstring () + " ; " ;
48 If (Domain ! = Null )
49 Cookie + = " Domain = " + Domain + " ; " ;
50 If (Path ! = Null )
51 Cookie + = " Path = " + Path + " ; " ;
52 Document. Cookie = Cookie;
53 };
54 This . Expire = Function (Key)
55 {
56 Expire_time = New Date ();
57 Expire_time.setfullyear (expire_time.getfullyear () - 1 );
58 VaR Cookie = " " + Key + " = E; expires = " + Expire_time + " ; "
59 Document. Cookie = Cookie;
60 }
61 }< P>
usage:
1. Set cookie
var cookie = new jscookie ();
// common setting
cookie. setcookie ("key1", "val1");
// The expiration time is one year
var expire_time = new date ();
expire_time.setfullyear (expire_time.getfullyear () + 1);
cookie. setcookie ("key2", "val2", expire_time);
// set the domain and path with the expiration time
cookie. setcookie ("key3", "val3", expire_time, ".cnblogs.com", "/");
// set the cookie of the BIND key, the subkeys are K1, K2, and K3
cookie. setcookie ("key4", "k1 = 1 & k2 = 2 & K3 = 3 ");
2. Read the cookie
// obtain the cookie.
. getcookie ("key1");
cookie. getcookie ("key2");
cookie. getcookie ("key3");
cookie. getcookie ("key4");
// obtain the key 1 Value of key4
cookie. getchild ("key4", "K1");
3. Delete
cookie. expire ("key1");
cookie. expire ("key2");
cookie. expire ("key3");
cookie. expire ("key4");