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

前言

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

}

密码校验

//密码必须包含大小写、数字和特殊字符,长度至少为8位
function checkPassword(passwrod){
    
    
let regexp = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/)
if(regexp.test(password)){
    
    
console.log('密码格式正确')
}
}

邮箱格式校验

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)
}

猜你喜欢

转载自blog.csdn.net/weixin_47389477/article/details/140818255
今日推荐