生成随机字符串
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;
};
randomString(10) // pfkMfjEJ6x
randomString(20) // ce6tEx1km4idRNMtym2S
字符串首字母大写
const fistLetterUpper = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
fistLetterUpper('fatfish') // Fatfish
生成指定范围内的随机数
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNum(1, 10) // 6
randomNum(10, 20) // 11
打乱数组的顺序
const shuffleArray = (array) => {
return array.sort(() => 0.5 - Math.random())
}
let arr = [ 1, -1, 10, 5 ]
shuffleArray(arr) // [5, -1, 10, 1]
shuffleArray(arr) // [1, 10, -1, 5]
格式化货币
// 第一种方法
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'
// 第二种方法
const formatMoney = (money) => {
return money.toLocaleString()
}
formatMoney(123456789) // '123,456,789'
formatMoney(123456789.123) // '123,456,789.123'
formatMoney(123) // '123'