前端常用的小函数(3)---手机号

318 阅读1分钟

需求背景

根据产品的需求和安全性,对手机号花样展示。

关于手机号, 你可能需要一个MobileMaster

class MobileMaster {
  constructor({ mobile = '13322221111', isMobile = false, isFormat = false }) {
    this.mobile = mobile;
    this.isMobile = isMobile;
    this.isFormat = isFormat;
  }

  // 验证手机号
  validate() {
    const VALIDATE_REG = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[0-9]|18[0-9]|14[57]|19[89])[0-9]{8}$/;
    this.isMobile = VALIDATE_REG.test(this.mobile);
    return this;
  };

  // 手机号格式化
  format() {
    let { mobile, isFormat } = this;
    if (!mobile) return this;
    if (isFormat) {
      this.mobile = mobile.replace(/\s/g, '').substring(0, 11);
      return this;
    }
    const len = mobile.length;
    if (len > 3 && len < 8) {
      this.mobile = `${mobile.substr(0, 3)} ${mobile.substr(3)}`;
    } else if (len >= 8) {
      this.mobile = `${mobile.substr(0, 3)} ${mobile.substr(3, 4)} ${mobile.substr(7)}`;
    }
    return this;
  };

  // 手机号脱敏
  desensitize() {
    this.validate();
    if (!this.isMobile) throw Error('请输入正确的手机号');
    const DESENSITIZE_REG = /(\d{3})\d*(\d{4})/; // 脱敏正则
    this.mobile = this.mobile.replace(DESENSITIZE_REG, '$1****$2');
    return this;
  };

  // 手机号美化
  beautify() {
    this.validate();
    if (!this.isMobile) return false;
    this.desensitize();
    this.format();
    return this;
  }
}
 // 举个🌰
master1 = new MobileMaster({ mobile: '13122223333'})
const mobile1 = master1.beautify().mobile; 
// mobile1: 131 **** 3333

// 脱敏
master2 = new MobileMaster({ mobile: '13122223333'})
const mobile2 = master2.desensitize().mobile; 
// mobile2: 131****3333

// 3-4-4格式
master3 = new MobileMaster({ mobile: '13122223333'})
const mobile3 = master3.desensitize().mobile; 
// mobile3: 131 2222 3333

// 判断手机号是否有效
master4 = new MobileMaster({ mobile: '13122223333'})
const { isMobile } = master4.desensitize(); 

// isMobile: true