1. 正则表达式验证手机号码
验证正则解释
- 从头开始第一位是1;
- 第二位是3,4,5,7,8;
- 第三位到结尾是0 - 9 的数字。
function checkPhone(phone) {
// 验证电话号码手机号码,包含至今所有号段? ?
var ab = /^[1][3,4,5,7,8][0-9]{9}$/;
if (ab.test(phone) == false) {
layer.alert('请正确填写手机号码!', { icon: 5, offset: '200px' });
return false;
}
}
2.修复toFixed
function toFixed(n, s) {
s = Number(s) || 0;
// eslint-disable-next-line no-restricted-properties
let changenum = (parseInt(n * Math.pow(10, s) + 0.5, 10) / Math.pow(10, s)).toString();
let index = changenum.indexOf('.');
if (index < 0 && s > 0) {
changenum += '.';
for (let i = 0; i < s; i++) {
changenum += '0';
}
} else {
index = changenum.length - index;
for (let i = 0; i < (s - index) + 1; i++) {
changenum += '0';
}
}
return changenum;
}
3.正则表达式验证是否存在汉字
const CHINESE = /.*[\u4e00-\u9fa5]+.*$/;
// 判断是否存在汉字
function hasChinese(str) {
return CHINESE.test(str);
}
4.随机生成
// 定义组合的字符
const NUMS = '0123456789';
const NUMSANDLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
function randomStr(n, isPureNum = false) {
let possible = isPureNum ? NUMS : NUMSANDLETTERS;
let ret = '';
for (let i = 0; i < n; i++) {
ret += possible.charAt(Math.floor(Math.random() * possible.length));
}
return ret;
}
5.固定电话正则
const FIXPHONE = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;
6.邮箱正则
const EMAIL = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
7.判断是不是数字
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
7.判断小数是几位
function countDecimals(n) {
if (!this.isNumber(n)) {
n = parseFloat(n);
}
if (Math.floor(n) === n.valueOf()) {
return 0;
}
return n.toString().split('.')[1].length;
}
8.是否相等
function isEqual(a, b) {
let aProps = Object.getOwnPropertyNames(a);
let bProps = Object.getOwnPropertyNames(b);
if (aProps.length !== bProps.length) {
return false;
}
for (let i = 0, len = aProps.length; i < len; i++) {
let propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
9.金额格式
function moneyFormat(n) {
if (n === undefined || n === null || n === '') {
return '0';
}
let isStr = this.isString(n);
let isNum = this.isNumeric(n);
if (!isStr && !isNum) {
return '';
}
if (this.isString(n)) {
n = parseFloat(n);
}
if (Number.prototype.hasOwnProperty('toLocaleString')) {
return n.toLocaleString();
}
return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}