前端常用的封装方法(值得收藏)

avatar
作者
猴君
阅读量:0

前言

在前端开发中,不管是pc端还是移动端,都需要使用到一些方法,比如电话号码的校验,身份证号的校验,邮箱的校验,节流、以及输入框的防抖等,时间的格式封装(可以使用dayjs库实现),深拷贝,浅拷贝,防抖(可以使用[\[lodash\]](https://www.lodashjs.com/))

防抖

//防抖 //在一个事件触发的最后一次,按特定时间后执行 const debounce = (fn, time) => {   let timer   return function (...argu) {     if (timer) {       clearTimeout(timer)       timer = null     }     timer = setTimeout(() => {       fn(...argu)       clearTimeout(timer)       timer = null     }, time)   } } 

节流

export function useThrottle() {   const throttle = (fn, delay) => {     let timer = null;     return function () {       if (!timer) {         timer = setTimeout(() => {           fn.apply(this, arguments);           timer = null;         }, delay);       }     };   };     return { throttle }; }  

姓名的隐私正则

//两位名字,第二个字“*” //3个字的名字,中间“*” const samsung=(str)=>{   var replcenem='';   //三位姓名的中间变星号   if(str.length>=3){     replcenem=str.replace(/^(.+).(.)$/, "$1*$2");     return replcenem   }   if (str.length == 2){  //两位的姓名,后面以为变星号       var strSplit=str.split('');       var strSplitone = strSplit[0];       replcenem = strSplitone+'*';       return replcenem   }  } 

邮箱格式校验

function emailValidator(email){ 	if( typeof(email) =='string'){ 	let regexp = new RegExp(/^([a-zA-Z0-9_\-\.]+)@((\w+\.)+\w+)$/) 	if(regexp.test(email)){ 	console.log('邮箱输入正确') 	}else{ 	console.log('请输入正确的邮箱格式') 	} 	} } 

身份证号格式校验

function checkIdCard(val) { if(typeof(val)!='string'){ val+='' //使其变成string }   const idCardPattern = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;   if (!idCardPattern.test(val)) {     console.log('您输入的身份证号码不正确!');   } } 

手机格式校验

function phoneValidator (phone){ 	let regexp = new RegExp(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/) 	if(regexp.test(phone) ){ 	console.log('输入正确') 	}else{ 	console.log('手机格式错误') 	} } 

手机号隐私处理

//手机号隐私处理 export const handlePhone=(phone)=>{   if(!phone){     return '--'   }else{     return phone.substring(0,3)+'****'+phone.substring(7)   }    } 

普通车牌的校验

 const jiaoyan (chepai)=>{ /^[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[ABCDEFGHJKLMNOPQRSTUVWXY]{1}[0-9A-Z]{5}$/u let regexp = new RegExp(/^[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[ABCDEFGHJKLMNOPQRSTUVWXY]{1}[0-9A-Z]{5}$/u) return regexp.test(chepai) } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!