前端项目实用utils汇总

908 阅读1分钟

做项目,自己实现的一些常用的JS方法

一、判断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);
}

二、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;
  }
}

三、正则实用判断

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

四、节流sleep、关闭当前页面

/*
 * 等待函数 sleep
 * @param time 要获取的参数time
 * sleep(5000).then(() => {
    console.log('业务代码')
  })
 */
export function sleep(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}

/*
  * 关闭当前页面 closePage
*/
export function closePage() {
  const { userAgent } = navigator;
  if (userAgent.indexOf('Firefox') !== -1 || userAgent.indexOf('Chrome') !== -1) {
    window.history.back();
    window.close();
  } else if (userAgent.indexOf('Android') > -1 || userAgent.indexOf('Linux') > -1) {
    window.history.back();
    window.close();
  } else {
    window.opener = null;
    window.close();
  }
}