常用的正则匹配方法(手机号、身份证号、地址、url参数、去除空字

2020-04-07  本文已影响0人  jane819

export const noop = (f:any) => f

// 验证手机号
export const isPhone = (phone:string):boolean => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}

// 验证身份证号
export const isIdNumber = (number:string):boolean => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return reg.test(number)
}

// 验证地址
// export const validateAddress = (address:string):boolean => address === address
//   .replace(/(\d+)([^\d]+)/, '$1').replace(/([a-zA-Z]+)([^a-zA-Z]+)/, '$1')

export const isValidAddress = (address:string):boolean => {
  const reg = /[\u4e00-\u9fa5]/
  if (!reg.test(address)) {
    return address !== address.replace(/(\d+)([^\d]+)/, '$1').replace(/([a-zA-Z]+)([^a-zA-Z]+)/, '$1')
  }
  return reg.test(address)
}

export function getQueryString(name:string) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i') // 匹配目标参数
  const result = window.location.search.substr(1).match(reg) // 对querystring匹配目标参数
  if (result != null) {
    return decodeURIComponent(result[2])
  }
  return null
}

/**
 *去除空的字符串(根据提供特殊的字符串)
 */
export const trim = (datas:Record<string, any>, delimiters:any = '') => {
  const props:Record<string, any> = {}
  Object.entries(datas).forEach(([key, value]) => {
    if (value !== delimiters) {
      props[key] = value
    }
  })
  return props
}

/**
 * 设置cookie
 * @param name
 * @param value
 */
export function setCookie(name:string, value:string, days:number = 15) {
  const exp = new Date()
  exp.setTime(exp.getTime() + (days * 24 * 60 * 60 * 1000))
  document.cookie = `${name}=${escape(value)};expires=${exp.toUTCString()};path=/`
}

/**
 * 获取cookie
 * @param name
 */
export function getCookie(name:string) {
  const arr = document.cookie.match(new RegExp(`(^| )${name}=([^;]*)(;|$)`))
  if (arr != null) return unescape(arr[2]); return null
}

/**
 * 延迟函数
 * @param ms
 */
export function delay(ms: number) {
  return new Promise(r => setTimeout(r, ms))
}

/**
 * 类型判断
 * @param o
 */
export function toTypeof(o: any): string {
  if (typeof o !== 'object') {
    return (typeof o)
  }
  return Object.prototype.toString.call(o).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

上一篇下一篇

猜你喜欢

热点阅读