Utils工具方法集插件详解
var Utils = function(){};
Utils.text = {
stripTags: function (val) {
return val.replace(/<\/?[^>]+>/gi, ""); //正则表达式中的<\/?其实就是匹配</或<,后面的[^>]+其实就是匹配不是>的任何一个或多个字符,因此此正则可以匹配<div>,</div>,<input type="text" />,很明显,此方法是去掉标签的工具方法。
},
decodeHTML: function (val) { //html解码
var s = val;
s = s.replace(/</gi, "<");
s = s.replace(/>/gi, ">");
s = s.replace(/"/gi, "\""); //这里的"\""可以改成'"'
s = s.replace(/ /gi, " ");
s = s.replace(/'/gi, "'");
s = s.replace(/&/gi, "&");
return s;
},
encodeHTML: function (val) {
var s = val;
s = s.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/\"/g, """);
s = s.replace(/ /g, " ");
s = s.replace(/\'/g, "'");
return s;
},
trim: function (val) {
return val.replace(/(^\s*)|(\s*$)/g, "");
},
len: function (val) { //返回字符串的字节数,中文2个字节,其它1个字节
var len = 0;
for (var i = 0, l = val.length; i < l; i++) {
if (val.charCodeAt(i) > 255) {
len += 2;
} else {
len++;
}
}
return len;
},
lefts: function (val,len, isAddDot) { //从字符串左边开始截取指定的字符数
var str = val;
if (val.length > len) {
str = val.substring(0, len);
if (isAddDot) {
str += "...";
}
}
return str;
},
isNumber: function (val) { //判断字符串是否为纯数字
return (val.search(/^\d+$/g) == 0);
},
inStr: function (val,str, isCase) { //字符串val是否存在于另外一个字符串str中,isCase是否区分大小写
var v = val;
var m = (isCase) ? "" : "i"; //默认情况下,是不区分大小写的
var reg = new RegExp("\\b" + v + "\\b", m); // \b的意思是匹配一个单词边界,也就是指单词和空格间的位置。例如,“er\b”可以匹配“never”中的“er”,但不能匹配“verb”中的“er”。
return reg.test(str);
},
format: function (str) { //格式化这种结构的字符串:"{0} not quals {1}"。举个例子:Util.format("{0} not equals {1}", 5, 6),返回的结果:"5 not equals 6"。
var args = arguments;
var pattern = /{(\d)}/g; //此正则匹配{0},{1}。
return String(str).replace(pattern, function (match, subkey) {
subkey = parseInt(subkey, 10) + 1; //subkey就是匹配的第一个子表达式,这里就是数字
var value = args[subkey];
if(typeof value !== "undefined"){
return value;
}else{
return "";
}
});
}
};
Utils.Number ={
add: function (num, num1) { //两个浮点数相加
var m = 0, r1 = 0, r2 = 0;
var s1 = num.toString(), s2 = num1.toString();
try {
if (s1.indexOf(".") > -1) {
r1 = s1.split(".")[1].length; //小数点后面有多少位
}
} catch (e) {
r1 = 0;
}
try {
if (s2.indexOf(".") > -1) {
r2 = s2.split(".")[1].length;
}
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2)); //取两个浮点数,小数点后面位数最长的值,假如是3,那么m = 1000。
return (num * m + num1 * m) / m;
},
mul: function (num, num1) { //两个浮点数相乘
var m = 0, s1 = num.toString(), s2 = num1.toString();
try {
if (s1.indexOf(".") > -1) {
m += s1.split(".")[1].length; //把两个浮点数的小数点后面的位数相加
}
} catch (e1) {
}
try {
if (s2.indexOf(".") > -1) {
m += s2.split(".")[1].length;
}
} catch (e2) {
}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
},
div: function (num, num1) { //两个浮点数相除,num/num1
var t1 = 0, t2 = 0, r1, r2, s1 = num.toString(), s2 = num1.toString();
try {
if (s1.indexOf(".") > -1) {
t1 = s1.split(".")[1].length;
}
}
catch (e1) {
}
try {
if (s2.indexOf(".") > -1) {
t2 = s2.split(".")[1].length;
}
}
catch (e2) {
}
r1 = Number(s1.replace(".", ""));
r2 = Number(s2.replace(".", ""));
return (r1 / r2) * Math.pow(10, t2 - t1);
}
};
Utils.Date = {
dateDiff: function(dt1, dt2 ,interval){ // 两个日期相差多长时间,interval代表时间差类型:D(天),H(时),M(分),S(秒),T(毫秒)
var objInterval = {'D':1000 * 60 * 60 * 24 , 'H':1000 * 60 * 60 , 'M':1000 * 60 , 'S':1000 , 'T':1};
interval = interval.toUpperCase();
try{
return Math.round( (dt2.getTime() - dt1.getTime()) / objInterval[interval] );
}
catch (e)
{
return e.message;
}
}
};
Utils.Url={
query: function (key, url) { //获取url的指定查询参数
url = url || location.href;
var reg = new RegExp('[?&]' + key + '=([^&#]*)'); //获取url上面指定的key值
var match = url.match(reg);
if (match) {
try {
return decodeURIComponent(match[1]); //取到的值需要解码
} catch (e) {
}
}
return "";
},
getUrlQueryParams:function(url){ //获取url的所有查询参数
var params = {};
url = url || location.href;
var regex = /[?&]([\w]+)=([^&#]*)/g; //第一个子表达式匹配key,第二个子表达式匹配value
while( ( results = regex.exec( url ) ) != null ){
params[decodeURIComponent(results[1])]=decodeURIComponent(results[2]);
}
return params;
},
addParameter: function ( url , key, value) { //给url添加查询字符串
url = url || location.href;
if(url.indexOf("#") != -1) {url = url.split("#")[0];var hash = url.split("#")[1];}
if (url.indexOf("?") == -1) url += "?"; //如果没有?,就证明原来的url没有查询字符串,因此加上?
if (url.indexOf(key + "=") == -1) { //如果url之前没有这个key值,就直接把这个查询字符串添加到url后面
return url + '&' + key + "=" + encodeURIComponent(value) + (hash ? hash : "");
} else { //如果url之前有这个key值,那么就替换掉
return url.replace(new RegExp("([?&])" + key + "=[^&]*"), "$1" + key + "=" + encodeURIComponent(value)) + (hash ? hash : "");
}
}
};
Utils.cookie = {
get: function (key) { //获取cookie中的name值
var cookie = document.cookie,cookieName = encodeURIComponent(key) + '=', //首先先获得cookie值
start = cookie.indexOf(cookieName), //再看cookie中是否有key值
value = null;
if (start > -1) {
var cookieEnd = document.cookie.indexOf(';', start);; //cookie中的值都是以";"隔开的,因此取到此值的结束点
if (cookieEnd == -1) { //如果此key值在cookie的最后面,就不会有";"。
cookieEnd = document.cookie.length;
}
value = decodeURIComponent(document.cookie.substring(start + cookieName.length, cookieEnd));
}
return value;
},
set: function (name, value, expires, path, domain, secure) { //设置cookie的值
var text = encodeURIComponent(name) + '=' + encodeURIComponent(value);
if (expires instanceof Date) {
text += ';expires=' + expires.toGMTString();
}
if (path) {
text += ';path=' + path;
}
if (domain) {
text += ';domain=' + domain;
}
if (secure) {
text += ';secure';
}
document.cookie = text;
},
unset: function (name, path, domain, secure) { //删除cookie,其实就是设置它超时
this.set(name, "", new Date(0), path, domain, secure);
}
};
Utils.event ={
preventDefault: function (event) {
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
},
stopPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
}
else {
event.cancelBubble = true;
}
},
getEvent: function (event) {
var e = event || window.event;
if (e.srcElement) e.target = e.srcElement;
return e;
}
};
加油!