# 验证相关
手机、数字、邮件等处理, 一些基础验证,方便大家使用。
# 手机号中间段加*号
export const hideMobile = (mobile) => {
return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}
是否为中国大陆手机号
export const isTel = (value) => {
return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.toString());
}
# 校验是否为邮箱地址
export const isEmail = (value) {
return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
}
是否为中国大陆的邮政编码
export const isPostCode = (value) => {
return /^[1-9][0-9]{5}$/.test(value.toString());
}
# 校验身份证号码
export const checkCardNo = (value) => {
let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
return reg.test(value);
};
# 校验是否包含中文
export const haveCNChars => (value) => {
return /[\u4e00-\u9fa5]/.test(value);
}
# 数字转化为中文数字
export 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]]
}
}
});
}
# 数字转化为大写金额
export 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(/^整$/, '零元整');
};
# 金额格式化
{number} number:要格式化的数字
{number} decimals:保留几位小数
{string} dec_point:小数点符号
{string} thousands_sep:千分位符号
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
number = (number + '').replace(/[^0-9+-Ee.]/g, '')
const n = !isFinite(+number) ? 0 : +number
const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
const dec = typeof dec_point === 'undefined' ? '.' : dec_point
let s = ''
const toFixedFix = function(n, prec) {
const k = Math.pow(10, prec)
return '' + Math.ceil(n * k) / k
}
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
const re = /(-?\d+)(\d{3})/
while (re.test(s[0])) {
s[0] = s[0].replace(re, '$1' + sep + '$2')
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
moneyFormat(10000000) // 10,000,000.00
moneyFormat(10000000, 3, '.', '-') // 10-000-000.000
格式化货币 2
const formatMoney = (money) => {
return money.replace(new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',')
}
formatMoney('123456789') // '123,456,789' formatMoney('123456789.123') // '123,456,789.123'
formatMoney('123') // '123
格式化货币 3
const formatMoney = (money) => { return money.toLocaleString() }
formatMoney(123456789) // '123,456,789' formatMoney(123456789.123) // '123,456,789.123'
formatMoney(123) // '123'
# 生成指定范围内的随机数
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNum(1, 10) // 6
randomNum(10, 20) // 11
# 数字数组求平均值
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
# 数字数组求和
console.log(
[1, 2, 3, 4].reduce((a, b) => a + b, 0)
)//10
# 校验数字是奇数还是偶数
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: True
# 检查字符串是否为有效数字
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
# 检查两个数字是否彼此近似相等,差异很小
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
# 小数点后两位
parseFloat("183.456").toFixed(2);
使用MathRound:
Math.round( num * 100 + Number.EPSILON ) / 100
将字符串转换为十进制:
var string = 10.134.toFixed(2); // => '10.13'
var num = Number(string); // => 10.13
# 数字增长动画
封装 JS 组件
export const useNumberAnimation = options => {
const { form, to, duration, onProgress } = options
let value = form
//算出增长速度
const speed = (to - form) / duration
//起始时间
const startTime = Date.now()
const run = () => {
const t = Date.now() - startTime
//当时间间隔大于延迟时间时终止
if (t >= duration) {
value = to
onProgress?.(value)
return
}
//当前值=超始值+时间间隔*增长速度
value = form + t * speed
onProgress?.(value)
//继续执行
requestAnimationFrame(run)
}
run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
使用方式如下
<template>
<div class="flex justify-center">{{ num }}</div>
</template>
<script setup>
import { ref } from 'vue'
import { useNumberAnimation } from './use-number-animation' //这个是引入上面的JS组件
const num = ref('0')
useNumberAnimation({
form: 0,
to: 378291.61,
duration: 3000,
onProgress: v => {
console.log(`此时的值是:${v}`)
num.value = v.toFixed(2)
}
})
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19