前端常用的封装方法(值得收藏)
创始人
2024-11-15 01:32:25

前言

在前端开发中,不管是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) } 

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...