手机号码处理
function phoneStyle(phonestr){
phonestr = phonestr+'';
if(!phone || phone.length != 11) return '输入的是非法手机号!'
return phonestr.substring(0,3)+" **** "+phonestr.substring(7,11)
}
phoneStyle2(13612312312)
function phoneStyle(phone,type) {
phone = phone + '';
if (!phone || phone.length != 11) return '输入的是非法手机号!'
return phone.replace(/(?=(\d{4})+$)/g, type);
}
phoneStyle(13612312312,"-")
复制代码
数字处理
value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$')
.replace(/\./g, '').replace('$#$', '.')
.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')
复制代码
数字位数不够,进行前补字符串
function PrefixZero(num, n,type) {
return (Array(n).join(type) + num).slice(-n);
}
PrefixZero(9, 3,0)
PrefixZero(12,3,"*")
复制代码
去除字符串指定字符
let str = 'abcd,abcd,dcab';
str = str.replace(/^(\s|ab)+|(\s|ab)+$/g, '');
复制代码
生成随机颜色
let colorList =[];
for(let i=0;i<6;i++){
colorList.push('#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0'))
}
复制代码
生成随机ID
Math.random().toString(36).substring(2)
复制代码
每秒更新当前时间
setInterval(()=>document.body.innerHTML=new Date().toLocaleString())
复制代码
金钱格式化
let money = '1234567890'
let format = money.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format)
复制代码
递归求阶乘
let factorial = (n)=> (n > 1) ? n * factorial(n - 1) : n
factorial(5)
复制代码
vue阻止事件冒泡
aaa(e) {
e.stopPropagation();
...
},
复制代码
js来控制字符串的长度
function ellipsisText(str, num) {
if (str && str.length >= num) {
str = str.substr(0, num) + '...'
}
return str;
}
复制代码
for循环的特殊写法
for (语句 1; 语句 2; 语句 3)
{
被执行的代码块
}
for(let i=0;i<10;i++){
console.log(i);
}
for(var i=10;i--;){
console.log(i);
}
for (var i = 0, rule; rule = rules[i++];) {
}
复制代码
去掉小数部分
parseInt(num)
~~num
num >> 0
num | 0
复制代码
解构字符串成数组
[...'abcdefg']
复制代码
允许滑动和禁止滑动
stopMove() {
document.body.style.overflow = "hidden";
document.addEventListener("touchmove", (e)=> e.preventDefault(), { passive: false });
},
Move() {
document.body.style.overflow = "";
document.removeEventListener("touchmove", (e)=> e.preventDefault(), { passive: true });
},
复制代码
(?.)操作符号和?? 操作符
const user = {
name: "lf",
type: {
age: 12
},
list: [{name: "lf"}, {name: "lf1"}],
getName: function(){
return this.name;
}
}
user.name1;
user?.name1;
user.type.age1;
user.type?.height;
user.getName1();
user.getName1?.();
user.list1[3].name;
user.list1[3]?.name;
user?.name1??"lf";
复制代码
创建目录
const fs = require('fs');
const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
createDirIfNotExists('dir1');