一些常用的JS方法
只能输入数字汉子英文
function ($str) {
var regu = "^[0-9a-zA-Z\u4e00-\u9fa5]+$";
var re = new RegExp(regu);
if ($str == "") {
layer.msg('不能为空', { icon: 5 });
return false;
}
else if (!re.test($str)) {
layer.msg('不能包含特殊字符.', { icon: 5 });
return false;
}
return true;
}
计算两段时间差(输出单位为秒)
//eg:stime='10:10:10';etime='11:20:20'
function (stime, etime) {
if (typeof (stime) != 'string' || typeof (etime) != 'string')
return false;
var reg = /^(\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var sr = stime.match(reg);
if (sr == null) return false;
var sd = new Date(0, 0, 0, sr[1], sr[2], sr[3]);
var er = etime.match(reg);
if (er == null) return false;
var ed = new Date(0, 0, 0, er[1], er[2], er[3]);
return (ed - sd) / 1000;
}
生成GUID
//生成GUID
function uuid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
//return uuid.replace(new RegExp("-", 'g'), "");
}
生成文件流的MD5
//获取文件流的MD5加密,参数是上传的文件的file对象调用file.slice()方法
function GetFileMd5(blob) {
var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onloadend = function (e) {
var md5 = hex_md5(e.target.result);
console.log(md5);
}
}
实现HTML标签转义
function html_encode(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/ /g, " ");
s = s.replace(/\'/g, "'");
s = s.replace(/\"/g, """);
s = s.replace(/\n/g, "<br/>");
return s;
}
实现HTML标签反转义
function html_decode(str)
{
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/ /g, " ");
s = s.replace(/'/g, "\'");
s = s.replace(/"/g, "\"");
s = s.replace(/<br\/>/g, "\n");
return s;
}
ES6对数组操作的一些方法
var list= [
{ id: 1, name: '奔驰' },
{ id: 2, name: '宝马' }
];
var car = { id: 3, name: '奥迪'};
//追加到数组后面的方法
list.push(car);
//对数组遍历过滤的方法
var Slist = list.filter(item=>{
if(item.name.includes('宝'))
return item;
});
//查找数组满足条件返回索引的方法
var index = list.findIndex(item => {
if (item.id == 1)
return true;
});
//根据索引值删除数据的方法
list.splice(index, 1)