手机号中间四位变成*
const telFormat = (tel) => {
tel = String(tel);
return tel.substr(0,3) + "****" + tel.substr(7);
};
校验是否为中国大陆手机号
const isTel = (value) => {
return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.toString());
}
截取字符串
const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;
校验是否包含中文
const haveCNChars = (value) => {
return /[\u4e00-\u9fa5]/.test(value);
}
校验是否为邮箱地址
const isEmail = (value) {
return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
}
字符串首字母大写
const fistLetterUpper = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
数字千分位分隔
const numberFormat = (value) {
if (value == null || value == "") return "0"; //进行输入内容判断
if (value) {
value += "";
if (!value.includes(".")) value += ".";
return value.replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
return $1 + ",";
}).replace(/\.$/, "");
}
}
数字千分位分隔(保留两位小数)
const numberFormat2 = (value) {
if (value == null || value == "") return "0";//进行输入内容判断
if (value) {
return Number(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
return $1 + ",";
}).replace(/\.$/, "");
}
}
数组中获取随机数
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
数组去重
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3]));//[1,2,3]
合并数组
const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];
生成随机长度字符串
const randomString = (len) => {
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
let strLen = chars.length;
let randomStr = '';
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;
};
数字转化为大写金额
const digitUppercase = (n) => {
const fraction = ['角', '分'];
const digit = [
'零', '壹', '贰', '叁', '肆',
'伍', '陆', '柒', '捌', '玖'
];
const unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
n = Math.abs(n);
let 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++) {
let p = '';
for (let 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 s.replace(/(零.)*零元/, '元')
.replace(/(零.)+/g, '零')
.replace(/^整$/, '零元整');
};
数字转化为中文数字
const intToChinese = (value) => {
const str = String(value);
const len = str.length-1;
const idxs = ['','十','百','千','万','十','百','千','亿','十','百','千','万','十','百','千','亿'];
const num = ['零','一','二','三','四','五','六','七','八','九'];
return str.replace(/([1-9]|0+)/g, ( $, $1, idx, full) => {
let pos = 0;
if($1[0] !== '0'){
pos = len-idx;
if(idx == 0 && $1[0] == 1 && idxs[len-idx] == '十'){
return idxs[len-idx];
}
return num[$1[0]] + idxs[len-idx];
} else {
let left = len - idx;
let right = len - idx + $1.length;
if(Math.floor(right / 4) - Math.floor(left / 4) > 0){
pos = left - left % 4;
}
if( pos ){
return idxs[pos] + num[$1[0]];
} else if( idx + $1.length >= len ){
return '';
}else {
return num[$1[0]]
}
}
});
}
判断是移动还是PC设备
const isMobile = () => {
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
return 'mobile';
}
return 'desktop';
}
判断是否是苹果还是安卓移动设备
const isAppleMobileDevice = () => {
let reg = /iphone|ipod|ipad|Macintosh/i;
return reg.test(navigator.userAgent.toLowerCase());
}
判断是否是安卓移动设备
const isAndroidMobileDevice = () => {
return /android/i.test(navigator.userAgent.toLowerCase());
}
滚动到页面顶部
const scrollToTop = () => {
const height = document.documentElement.scrollTop || document.body.scrollTop;
if (height > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, height - height / 8);
}
}
滚动到页面底部
const scrollToBottom = () => {
window.scrollTo(0, document.documentElement.clientHeight);
}
滚动到指定元素区域
const smoothScroll = (element) => {
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
};
打开浏览器全屏
const toFullScreen = () => {
let element = document.body;
if (element.requestFullscreen) {
element.requestFullscreen()
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen()
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen()
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen()
}
}
退出浏览器全屏
const exitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen()
} else if (document.msExitFullscreen) {
document.msExitFullscreen()
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen()
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen()
}
}
当前时间
const nowTime = () => {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth();
const date = now.getDate() >= 10 ? now.getDate() : ('0' + now.getDate());
const hour = now.getHours() >= 10 ? now.getHours() : ('0' + now.getHours());
const miu = now.getMinutes() >= 10 ? now.getMinutes() : ('0' + now.getMinutes());
const sec = now.getSeconds() >= 10 ? now.getSeconds() : ('0' + now.getSeconds());
return +year + "年" + (month + 1) + "月" + date + "日 " + hour + ":" + miu + ":" + sec;
}
计算两个时间的间隔
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime())
dayDif(new Date("2021-11-3"), new Date("2022-2-1"))
格式化时间
const dateFormater = (formater, time) => {
let date = time ? new Date(time) : new Date(),
Y = date.getFullYear() + '',
M = date.getMonth() + 1,
D = date.getDate(),
H = date.getHours(),
m = date.getMinutes(),
s = date.getSeconds();
return formater.replace(/YYYY|yyyy/g, Y)
.replace(/YY|yy/g, Y.substr(2, 2))
.replace(/MM/g,(M<10 ? '0' : '') + M)
.replace(/DD/g,(D<10 ? '0' : '') + D)
.replace(/HH|hh/g,(H<10 ? '0' : '') + H)
.replace(/mm/g,(m<10 ? '0' : '') + m)
.replace(/ss/g,(s<10 ? '0' : '') + s)
}
// dateFormater('YYYY-MM-DD HH:mm:ss')
// dateFormater('YYYYMMDDHHmmss')
阻止冒泡事件
const stopPropagation = (e) => {
e = e || window.event;
if(e.stopPropagation) { // W3C阻止冒泡方法
e.stopPropagation();
} else {
e.cancelBubble = true; // IE阻止冒泡方法
}
}