您的位置:首页 > Web前端 > JavaScript

js的一些常用方法,保存cookie等

2016-01-07 13:57 501 查看
分享你一个在工作能用到的js方法

// 添加Cookie
function addCookie(name, value, options) {
if (arguments.length > 1 && name != null) {
if (options == null) {
options = {};
}
if (value == null) {
options.expires = -1;
}
if (typeof options.expires == "number") {
var time = options.expires;
var expires = options.expires = new Date();
expires.setTime(expires.getTime() + time * 1000);
}
document.cookie = encodeURIComponent(String(name)) + "=" + encodeURIComponent(String(value)) + (options.expires ? "; expires=" + options.expires.toUTCString() : "") + (options.path ? "; path=" + options.path : "") + (options.domain ? "; domain=" + options.domain : ""), (options.secure ? "; secure" : "");
}
}

// 获取Cookie
function getCookie(name) {
if (name != null) {
var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
return value ? decodeURIComponent(value[1]) : null;
}
}

// 移除Cookie
function removeCookie(name, options) {
addCookie(name, null, options);
}

//js模拟StringBuffer
function StringBuffer() {
this.__strings__ = new Array;
}

StringBuffer.prototype.append = function (str) {
this.__strings__.push(str);
};

StringBuffer.prototype.toString = function () {
return this.__strings__.join("");
};

String.prototype.replaceAll = function(s1,s2){
      return this.replace(new RegExp(s1,"gm"),s2);
}

//去空取值
function getStringNoNull(s){
if(s==null || s==undefined)
{
return "";
}else{
return s;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: