JavaScript常用工具类整理(总结版)
Posted 孙叫兽
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript常用工具类整理(总结版)相关的知识,希望对你有一定的参考价值。
导读:在前端开发过程中需要对常用的功能模块进行封装,常用的方法多次调用需要整合,保证组件的复用性与程序的可维护性,这里总结一下,便于后续的使用!
目录
14.文本输入校验(中文、数字、字母、下划线、中文标点符号。 ; , : “ ”( ) 、 ? 《 》)
15.左填充(str 原字符串,len 目标长度,pad 填充的字符(默认:空格))
22.金额自动加","分割(v_money 要格式化的金额,need_dot 是否需要精确到小数点后2位,{String} 格式化以后的金额,如:1,234,567.08)
24.生成验证码(len 验证码长度(默认:6),{String} 生成的验证码,)
26.格式化户名显示,2字屏蔽第1位,用*号代替,3字屏蔽第2位,用*号代替,3字以上,显示第1位和最后1位,其余用*号代替,最多使用5位*。
28.生成UUID(len UUID长度,默认标准36位,radix UUID基数,默认16)
36.按多长间隔截取字符串,n为长度,返回按长度分割成的字符串数组
39.计算总页数,根据总条数和每页显示数(totalpage:总条数,pagesize:每页显示条数)
40.将‘YYYYMMDD’格式的字符串格式化成‘YYYY-MM-DD’的格式
50.获取JS字符串字节数,str 要计算的字符串(str的字节数,中文占2个字节,英文占1个字节)
53.hex -> dsp(hex 十六进制压缩码 如[0x12, 0x34, 0x56], dsp 如 "123456")
55.分量亦或合成(itemA 分量A,itemB 分量B,bDsp 是否扩展 true,则传入的itemA与itemB与返回的合成变量都为扩展码,否则都为Uint8Array类型的压缩码数组)
1.全局声明工具类
window.$App = window.$App || {};
window.$App.AppUtils = (function () {
let apputils = {};
}
2.定时器
/**
* 定时器
* @class Timer
*/
apputils.Timer = ClassLoader.create();
apputils.Timer.prototype = {
initialize: function ($, A, _) {
this._h = null;
this.callback = $;
this.interval = A;
this.loop = _ ? true : false;
this.running = false
},
onTimer: function () {
if (!this.running) {
try {
this.running = true;
this.callback();
} finally {
this.running = false;
}
}
if (this.loop == false) {
this.stop();
}
},
stop: function () {
clearInterval(this._h);
},
start: function () {
this.stop();
this._h = setInterval(this.onTimer.bind(this), this.interval * 1000);
}
};
/**
* 启动定时器
* @param {*} times 倒计时时间,单位:秒
* @param {*} callback 倒计时完成回调函数
* @param {*} repeat 是否循环执行
* @returns {object} 定时器对象,支持方法:start、stop
* @function startTimer
*/
apputils.startTimer = function (times, callback, repeat) {
try {
var timer = new this.Timer(function () {
callback();
}, times, repeat);
timer.start();
return timer;
} catch (ajaxException) {
alert(ajaxException.message);
}
return null;
};
3.判断变量是否是一个值
function (o) {
return typeof (o) !== 'undefined' && o !== null ? true : false;
};
4.判断变量是否为空
function (val) {
var regu = "^[ ]+$";
var re = new RegExp(regu);
return val == null || typeof (val) == 'undefined' || val == "" || re.test(val);
};
5.判断变量是否为一个数组
function (o) {
return this.isvalue(o) ? Object.prototype.toString.apply(o) === '[object Array]' :
false;
};
6.输入对象
function (o) {
return this.isarray(o) ? o.length : -1;
};
7.将object对象转化为数组
function (o) {
return this.isarray(o) ? o : new Array();
};
8.对象转字符串
function (o) {
var str = "";
if (this.isvalue(o)) {
var t = Object.prototype.toString.apply(o);
if (t === '[object Array]') {
let a = [];
for (var i = 0; i < o.length; i++) {
/**
* 此处原方法为a.push(this.tostring(o[i]));
* 当o为字符串数组是,返回的结果出错,因此做了如下修改
*/
if (this.tostring(o[i]).charAt(0) == '{') { //o为json数组时
a.push(this.tostring(o[i]));
} else { //o为字符串数组时
a.push('"' + this.tostring(o[i]) + '"');
}
}
str = '[' + a.join(',') + ']';
a.length = 0;
// a = null;
} else if (t === '[object Date]') {
var y = o.getFullYear();
if (y < 1900) {
y += 1900;
}
var m = o.getMonth() + 1;
str = y + "-" + this.lpad(m, 2, '0') + "-" +
this.lpad(o.getDate(), 2, '0') + " " +
this.lpad(o.getHours(), 2, '0') + ":" +
this.lpad(o.getMinutes(), 2, '0') + ":" +
this.lpad(o.getSeconds(), 2, '0');
} else if (t === '[object Object]') {
let a = [],
k;
for (k in o) {
var vt = Object.prototype.toString.apply(o[k]);
if (vt === '[object Array]' || vt === '[object Object]') {
a.push('"' + k + '":' + this.tostring(o[k]));
} else {
a.push('"' + k + '":"' + this.tostring(o[k]) + '"');
}
}
str = '{' + a.join(',') + '}';
a.length = 0;
// a = null;
} else {
str = String(o);
}
}
return str;
};
9.json字符串转json对象
function (str) {
if (str == null || str == "") {
return "";
}
if (str.charAt(0) != '(') {
str = "(" + str + ")";
}
return eval(str);
};
10.判断是否为数字
function (str) {
var regu = /^(\\d+)$/;
return regu.test(str);
};
11.判断是否为整型
function (str) {
var regu = /^[-]{0,1}[0-9]{1,}$/;
return regu.test(this.val(str));
};
12.判断是否为浮点型
function (str) {
if (this.isint(str))
return true;
var re = /^[-]{0,1}(\\d+)[.]+(\\d+)$/;
if (re.test(str)) {
if (RegExp.$1 == 0 && RegExp.$2 == 0)
return false;
return true;
} else {
return false;
}
};
13.手机号验证
function (s) {
var patrn = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\\d{8}$/;
return patrn.exec(s);
};
14.文本输入校验(中文、数字、字母、下划线、中文标点符号。 ; , : “ ”( ) 、 ? 《 》)
function (s) {
var patrn = /^[\\u4e00-\\u9fa5_a-zA-Z0-9_\\u3002\\uff1b\\uff0c\\uff1a\\u201c\\u201d\\uff08\\uff09\\u3001\\uff1f\\u300a\\u300b]*$/;
return patrn.exec(s);
};
15.左填充(str 原字符串,len 目标长度,pad 填充的字符(默认:空格))
function (str, len, pad) {
str = this.tostring(str);
if (typeof (len) === "undefined") {
len = 0;
}
if (typeof (pad) === "undefined") {
pad = ' ';
}
if (len + 1 >= str.length) {
str = Array(len + 1 - str.length).join(pad) + str;
}
return str;
};
16.右填充
function (str, len, pad) {
str = this.tostring(str);
if (typeof (len) === "undefined") {
len = 0;
}
if (typeof (pad) === "undefined") {
pad = ' ';
}
if (len + 1 >= str.length) {
str = str + Array(len + 1 - str.length).join(pad);
}
return str;
};
17.消除空格
function (text) {
return (text || "").replace(/^\\s+|\\s+$/g, "");
};
18.json对象转form数据
function (json) {
var str = "";
for (var i in json) {
str += "&" + i + "=" + json[i];
}
if (str.length > 1) {
str = str.substring(1);
}
return str;
};
19.IP有效验证
function (ip) {
var re = /(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)/g; //匹配IP地址的正则表达式
if (re.test(ip)) {
var arr = ip.split(".");
if (arr[0] > 254 || arr[1] > 254 || arr[2] > 254 || arr[3] > 254)
return false;
return true;
} else {
return false;
}
}
20.ASCII转HEX
function (str) {
if (!this.isvalue(str)) {
return "";
}
var hex = "";
for (var i = 0; i < str.length; ++i) {
hex += str.charCodeAt(i).toString(16);
}
return hex;
}
21.HEX转ASCII
function (hex) {
if (!this.isvalue(hex) || hex.length % 2 != 0) {
return "";
}
var str = "";
for (var i = 0; i < hex.length / 2; ++i) {
var tmp = "0x" + hex[i * 2] + hex[i * 2 + 1];
var charValue = String.fromCharCode(Number(tmp));
str += charValue;
}
return str;
}
22.金额自动加","分割(v_money 要格式化的金额,need_dot 是否需要精确到小数点后2位,{String} 格式化以后的金额,如:1,234,567.08)
function (v_money, need_dot) {
try {
var p_number = parseFloat(v_money);
if(isNaN(p_number)) {
return v_money;
}
var p_string = "" + p_number;
var p_idx = p_string.lastIndexOf(".");
if (p_idx < 0) {
p_idx = p_string.length;
p_string = p_string + ".00";
} else {
var sarray = p_string.split('.');
if (sarray[1] == '') {
p_string = p_string + "00";
} else if (sarray[1].length == 1) {
p_string = p_string + "0";
}
}
var p_ret = p_string.substring(p_idx);
var p_temp = p_string.substring(0, p_idx);
var p_length = p_temp.length;
var p_count = Math.ceil(p_length / 3);
for (var p_i = 0; p_i < p_count; p_i++) {
var p_start_i = p_length - (p_i + 1) * 3;
p_ret = p_temp.substring(p_start_i, p_start_i + 3) + p_ret;
if (p_i < p_count - 1) {
p_ret = "," + p_ret;
}
}
if (need_dot == false) {
var len = p_ret.indexOf(".");
p_ret = p_ret.substring(0, len);
}
return p_ret;
} catch (p_ee) {
return "";
}
};
23.把金额数字转换为中文大写金额
function (n) {
var fraction = ['角', '分'];
var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
var unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
var head = n < 0 ? '欠' : '';
n = Math.abs(n);
var s = '';
for (let i = 0; i < fraction.length; i++) {
s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (let i = 0; i < unit[0].length && n > 0; i++) {
var p = '';
for (var j = 0; j < unit[1].length && n > 0; j++) {
p = digit[n % 10] + unit[1][j] + p;
n = Math.floor(n / 10);
}
s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
}
return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
};
24.生成验证码(len 验证码长度(默认:6),{String} 生成的验证码,)
function (len) {
var charactors = "1234567890";
var value = '';
if (!this.isint(len)) {
len = 6;
}
for (let j = 1; j <= len; j++) {
var i = parseInt(10 * Math.random());
value = value + charactors.charAt(i);
}
return value;
};
25.格式化账号显示(4位加空格)
function (account) {
if (!this.isvalue(account)) {
return "";
}
if(account.startsWith("1")){
if(account.length >= 17){
account=account.substring(0,6)+"******"+account.substring(account.length-5);
}
}
if(account.startsWith("6")){
if(account.length >= 16){
account=account.substring(0,4)+" **** **** "+account.substring(account.length-4);
}
}
return account;
};
26.格式化户名显示,2字屏蔽第1位,用*号代替,3字屏蔽第2位,用*号代替,3字以上,显示第1位和最后1位,其余用*号代替,最多使用5位*。
function (name) {
if (!this.isvalue(name)) {
return "";
}
var res = "";
if (name.length == 1) {
res += name;
}
if (name.length == 2) {
res += "*";
res += name.substring(name.length - 1);
}
if (name.length == 3) {
res += name.substring(0, 1);
res += "*";
res += name.substring(2);
}
if (name.length > 3) {
res += name.substring(0, 1);
for(let i=0; i<name.length - 2; i++) {
if(i <= 4) {
res += "*";
} else {
break;
}
}
res += name.substring(name.length - 1, name.length);
}
return res;
};
27.字符串替换
function (sourceString, startPos, encryptCount, encryptChar) {
if (typeof sourceString != 'string')
return sourceString;
if (sourceString.length <= 0)
return sourceString;
if (typeof startPos != 'number')
return sourceString;
if (startPos <= 0)
return sourceString;
if (typeof encryptCount != 'number')
return sourceString;
if (encryptCount <= 0)
return sourceString;
if (startPos > sourceString.length)
return sourceString;
if ((startPos + encryptCount) > sourceString.length + 1)
return sourceString;
var str1 = sourceString.substr(0, startPos - 1);
var str2 = sourceString.substr(startPos - 1, sourceString.length - startPos + 1);
var str3 = '';
var str4 = str2.substr(encryptCount, str2.length - encryptCount);
for (var i = 0; i < encryptCount; i++) {
str3 = str3 + encryptChar;
}
return str1 + str3 + str4;
};
28.生成UUID(len UUID长度,默认标准36位,radix UUID基数,默认16)
function (len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = [],
i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
29.随机数生成36位UUID
function () {
var s4 = function () {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};
30.解析json,结果返回
function (str) {
if (typeof str == 'string') {
try {
var obj = JSON.parse(str);
if (typeof obj == 'object' && obj) {
return obj;
} else {
return false;
}
} catch (e) {
return false;
}
} else if (typeof str == 'object') {
console.log('It is a object already!');
return str;
}
console.log('It is not a string!')
};
31.金额数据分转元
function (money) {
if (typeof money == 'string') {
money = money.split(".").join("");//去调小数点
var money2 = parseInt(money);
money2 = money2.toString();
if (money2.length > 2) {
money2 = money2.substring(0, money2.length - 2) + "." + money2.substring(money2.length - 2, money2.length);
} else if (money2 == 0) {
money2 = "0.00";
} else if (money2.length == 2) {
money2 = "0." + money2;
} else if (money2.length == 1) {
money2 = "0.0" + money2;
}
return money2;
}
console.log('It is not a string!')
};
32.金额数据元转分
function (money) {
if (typeof money == 'string') {
var money2 = money.replaceAll(",", "");
if (money2.indexOf(".") < 0) {
money2 = money2 + "00"
} else if (money2.length - money2.indexOf(".") == 2) {//一位小数
money2 = money2.replace(".", "") + '0';
} else {//两位小数
money2 = money2.replace(".", "");
}
return money2;
}
console.log('It is not a string!')
};
33.两个浮点型相减,不丢失精度
function (arg1, arg2) {
var r1, r2, m, n;
try {
r1 = arg1.toString().split(".")[1].length
} catch (error) {
r1 = 0
}
try {
r2 = arg2.toString().split(".")[1].length
} catch (error) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2));
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
};
34. 两个浮点型相加,不丢失精度
function (arg1, arg2) {
var r1, r2, m, n;
try {
r1 = arg1.toString().split(".")[1].length
} catch (error) {
r1 = 0
}
try {
r2 = arg2.toString().split(".")[1].length
} catch (error) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2));
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m + arg2 * m) / m).toFixed(n);
};
35.按长度数组截取字符串,返回按长度分割成的字符串数组
function (str, lens) {
var arr = [];
var len = lens.length;
for (var i = 0; i < len; i++) {
if (str.length >= lens[i]) {
var strCut = str.substring(0, lens[i]);
arr.push(strCut);
str = str.substring(lens[i]);
} else {
// str = str;
arr.push(str);
}
}
return arr;
};
36.按多长间隔截取字符串,n为长度,返回按长度分割成的字符串数组
function (n) {
var str = this;
var arr = [];
var len = Math.ceil(str.length / n);
for (var i = 0; i < len; i++) {
if (str.length >= n) {
var strCut = str.substring(0, n);
arr.push(strCut);
str = str.substring(n);
} else {
// str = str;
arr.push(str);
}
}
return arr;
};
37.格式化字符串
function (fmtStr, obj) {
if (!fmtStr.formatStr) {
String.prototype.formatStr = function (argsObj) {
var regexp = /\\{(\\d+)\\}/g;
var args = argsObj || [];
var result = this.replace(regexp, function (m, i, o, n) {
// console.log(o + n)
return args[i];
});
return result.replace('%', "'");
};
}
return fmtStr.formatStr(obj);
};
38.存期格式化
function (trm) {
var trmStr = '';
console.log("trm==" + trm);
var trms = trm.split('D');
if (trms.length == 2 && trms[0].indexOf('M') != -1) {
var mon = trms[0].substring(1, trms[0].length);
console.log("mon==" + mon);
var month = parseInt(mon);
if (month < 12) {
if (month != 0) {
trmStr += month + "个月";
}
} else {
if (month % 12 == 0) {
trmStr += parseInt(month / 12) + "年";
} else {
trmStr += parseInt(month / 12) + "年" + parseInt(month % 12) + "个月";
}
}
if (parseInt(trms[1]) > 0) {
if (trmStr) {
trmStr += "零";
}
trmStr += parseInt(trms[1]) + "天";
}
}
return trmStr;
};
39.计算总页数,根据总条数和每页显示数(totalpage:总条数,pagesize:每页显示条数)
function (totalcount, pagesize) {
var p = (parseInt(totalcount) + parseInt(pagesize) - 1) / parseInt(pagesize);
return parseInt(p);
};
40.将‘YYYYMMDD’格式的字符串格式化成‘YYYY-MM-DD’的格式
function (dateStr) {
var date = dateStr;
if (date.length == 8) {
date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
}
return date;
};
41.理财,将币种(数字)转为汉字
function (ccycd) {
var ccycdstr = "";
switch (ccycd) {
case "156":
ccycdstr = "人民币元";
break;
case "250":
ccycdstr = "法国法郎";
break;
case "246":
ccycdstr = "马克";
break;
case "344":
ccycdstr = "香港元";
break;
case "392":
ccycdstr = "日元";
break;
case "826":
ccycdstr = "英镑";
break;
case "840":
ccycdstr = "美元";
break;
case "978":
ccycdstr = "欧元";
break;
default:
// ccycdstr = "";
break;
}
return ccycdstr;
}
42.H5获取自己本地IP地址
function grabLocalIps(onNewIP) { // onNewIp - your listener function for new IPs
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
var pc = new myPeerConnection({
iceServers: []
}), // 空的ICE服务器(STUN或者TURN)
noop = function () { },
localIPs = {}, //记录有没有被调用到onNewIP这个listener上
ipRegex = /([0-9]{1,3}(\\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
function ipIterate(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
pc.createDataChannel(""); //create a bogus data channel
var handle = function (sdp) {
sdp.sdp.split('\\n').forEach(function (line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(ipIterate);
});
pc.setLocalDescription(sdp, noop, noop);
}
// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
if (navigator.userAgent.match(/^volcano.*/) ||
navigator.userAgent.match(/Chrome\\/\\d*\\./) && navigator.userAgent.match(/Chrome\\/\\d*\\./)[0] <= 'Chrome/50.') {
pc.createOffer(handle);
} else {
pc.createOffer().then(handle); // create offer and set local description
}
pc.onicecandidate = function (ice) { //listen for candidate events
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
};
}
43.通过http请求获取文本数据
function (url, sendData) {
let promise = new Promise((resolve, reject) => {
try {
let response = "";
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.status == 200 || xmlhttp.status == 0) {
response = xmlhttp.responseText;
if ('' !== response) {
resolve({ status: xmlhttp.status, response });
}
} else if (xmlhttp.status == 400) {
console.warn("Bad Request(parameter is not json format)");
reject({ status: xmlhttp.status, response });
} else if (xmlhttp.status == 500) {
console.warn("Bad Request(parameter is not json array)");
reject({ status: xmlhttp.status, response });
} else {
reject({ status: xmlhttp.status, response });
}
}
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(sendData);
} catch (e) {
reject(e)
}
})
return promise
}
44.数组转对象
function (list, key) {
var object = {};
if (!list) {
return object;
}
for (var elemInx in list) {
var elem = list[elemInx];
if (!elem[key]) {
return null;
}
object[elem[key]] = elem;
}
return object;
}
45.精准乘法
function (arg1, arg2) {
let m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[1].length;
} catch (e) {
console.error("accMul.s1.split:", e);
}
try {
m += s2.split(".")[1].length;
} catch (e) {
console.error("accMul.s2.split:", e);
}
return (
(Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
Math.pow(10, m)
);
}
46.判断当前浏览器环境
function ($) {
if ($ == "ie") {
if (navigator.appName.indexOf("Microsoft") != -1)
return true
}
else if ($ == "ns")
if (navigator.appName.indexOf("Netscape") != -1)
return true;
return false
};
47. 播放语音(src 语音文件url)
function (src) {
let _ = window.document.getElementById("sound");
try {
if (this.env("ie")) {
if (_ == null) {
let bgSoundObj = window.document.createElement("bgsound")
bgSoundObj.id = "sound";
bgSoundObj.src = "";
_ = bgSoundObj;
}
_.src = src;
} else {
if (_ == null) {
let audioObj = window.document.createElement("audio")
audioObj.id = "sound";
audioObj.src = "";
_ = audioObj;
}
_.src 以上是关于JavaScript常用工具类整理(总结版)的主要内容,如果未能解决你的问题,请参考以下文章