JavaScript操作Cookie方法实例分析
本文实例讲述了JavaScript操作Cookie方法。分享给大家供大家参考。具体如下:
//Mymethodsforsetting,readinganddeletingcookies.
//Ihavemethodstocheckfortheexistenceofcookienamesorvalues,
//toretrievebynameorvalue,andtocreateaformattedstringof
//allthecookies.
//Mysite:andrew.dx.am
varSetCookie=function(name,value,expires,path,domain,secure){
//ThecallershouldTrimthename/valuepair,ifrequired.
//Setsthename/valuepair(encoded);'expires'istheno.ofdays.
varexpires_date;
if(expires){
expires_date=newDate();
expires_date.setDate(expires_date.getDate()+expires);
}
document.cookie=encodeURIComponent(name)+"="+
encodeURIComponent(value)+
((expires)?";expires="+expires_date.toUTCString():"")+
((path)?";path="+path:"")+
((domain)?";domain="+domain:"")+
((secure)?";secure":"");
};
varDeleteCookie=function(name,path,domain){
//ThecallershouldTrimthename/valuepair.
//Encodesthenamebeforedeleting.
document.cookie=encodeURIComponent(name)+"="+
((path)?";path="+path:"")+((domain)?";domain="+
domain:"")+";expires=Fri,01-Jan-201000:00:01UTC";
};
varDelAllCookies=function(){
varcurrDate=newDate(),i,theCookie=document.cookie.split(";");
currDate=currDate.toUTCString();
i=theCookie.length;
while(i--){
document.cookie=theCookie[i]+";expires="+currDate;
}
};
varEscapeReg=function(str){
//Helperfn:Escapescharactersforuseinaregularexpression.
returnstr.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");
};
//ThefollowingfourfunctionsdonotTrimthenameorvalue
//-thecallingfnsshoulddothis.
varCNameExists=function(cookie_name){//case-insensitive
vartestName,myReg;
if(document.cookie.length==0)returnfalse;
testName=EscapeReg(cookie_name);
myReg=newRegExp('(^|;)?'+testName+'=([^;]*)(;|$)','i');
returnmyReg.test(decodeURIComponent(document.cookie));
};
varCValueExists=function(cookie_value){//caseinsensitive
vartestName,myReg;
if(document.cookie.length==0)returnfalse;
testName=EscapeReg(cookie_value);
myReg=newRegExp('(=)'+testName+'(;|$)','i');
returnmyReg.test(decodeURIComponent(document.cookie));
};
varCNameGet=function(cookie_value){//case-insensitive
vartestName,myReg,results;
if(document.cookie.length==0)return'';
testName=EscapeReg(cookie_value);
myReg=newRegExp('(^|;)?([^=]*)='+testName+'(;|$)','i');
results=decodeURIComponent(document.cookie).match(myReg);
return(results)?results[2]:'';
};
varCValueGet=function(cookie_name){//case-insensitive
vartestName,myReg,results;
if(document.cookie.length==0)return'';
testName=EscapeReg(cookie_name);
myReg=newRegExp('(^|;)?'+testName+'=([^;]*)(;|$)','i');
results=decodeURIComponent(document.cookie).match(myReg);
return(results)?results[2]:'';
};
varCookieStr=function(){
//Returnsastring(withlinebreaks)whichcouldbe
//placedin,forexample,atextarea.
returndecodeURIComponent(document.cookie).
replace(/([^=;]+)=([^;]*)[;\s]*/g,'$1($2)\n')||'';
};
希望本文所述对大家的javascript程序设计有所帮助。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短