前端項目實用utils彙總

作項目,本身實現的一些經常使用的JS方法bash

1、判斷url

const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g;

export function isUrl(path) {
  return reg.test(path);
}
複製代碼

2、url獲取參數

export default class WebUtils {
  static getParamFromQueryString(key) {
    const queryString = window.location.search;
    if (queryString) {
      const reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`, 'i');
      const r = queryString.substr(1).match(reg);
      if (r !== null) return r[2];
    }
    return null;
  }
}
複製代碼

3、正則實用判斷

export default class CheckUtils {
  static checkMobile(mobile) { // 檢測手機
    return /^1[3|4|5|7|8]\d{9}$/.test(mobile);
  }
  
  static checkInt(num) { // 正整數
    return /^0|([1-9]\d*)\b/.test(mobile);
  }

  static checkEmail(email) {
    return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email);
  }

  static isEmail(email) {
    return /^\w+([-+.]\w+)*@163.com.cn$/.test(email);
  }

  static checkQQ(qq) {
    return /^\d{5,}$/.test(qq) || CheckUtils.checkEmail(qq);
  }

  static checkWechat(wx) {
    return CheckUtils.checkMobile(wx) || CheckUtils.checkEmail(wx) || CheckUtils.checkQQ(wx) || /^[a-zA-Z\d_]{5,}$/.test(wx);
  }

  static checkSmsCode(smsCode) {
    return /\d{6}/.test(smsCode);
  }

  static checkIdentityCode(identityCode) {
    return /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/.test(identityCode);
  }

  static checkName(name) {
    return /^[\u0391-\uFFE5A-Za-z0-9]+$/.test(name);
  }

  static checkPostCode(name) {
    return /^[1-9][0-9]{5}$/.test(name);
  }

  static numtoFixed(num) { // 千分位設置
    if (typeof num !== 'number') {
      return num;
    }
    let b = null;
    if (num.toString().indexOf('.') === -1) {
      b = (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    } else {
      b = num.toString().replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    }
    return b;
  }
  static twonumCheck(num) { // 千分位設置
    return /^\d+(\.\d{1,2})?$/.test(num);
  }
}
複製代碼
相關文章
相關標籤/搜索