常见正则应用

  1. \( 常见手机号处理 手机号格式化 \)
  • 手机号3-4-4分割
let mobile = '13312345678' 
let mobileReg = /(?=(\d{4})+$)/g 

console.log(mobile.replace(mobileReg, '-')) // 133-1234-5678
  • 手机号码中间四位数字用*表示
const phone = '13312345678'
const phoneReg = /^(\d{3})(\d{4})(\d{4})$/
const sp = phone.replace(phoneReg, '$1****$3')
// sp: 133****6789

也可以使用该正则表达3-4-4格式
const w = phone.replace(phoneReg, '$1-$2-$3')
$1--$9 是RegExp 自带的。代表的是 分组,即小括号里面的小正则 捕获到的内容 是用来表示正则表达式子表达式相匹配的文本。
这里的$1就是代表的就是第一个括号内的内容
  1. \( 提取连续重复的字符 \)
const collectRepeatStr = (str) => {
  let repeatStrs = []
  const repeatRe = /(.+)\1+/g
  
  str.replace(repeatRe, (old, txt) => {
    txt && repeatStrs.push(txt)
  })
  
  return repeatStrs
}
replace用法:stringObj.replace(regexp/substr,replacement)
replace方法不仅可以替换字符,也可以用来提取字符
  • 将数字转化为大写
var ary = ["一", "二", "三", "四", "五", "六"]
const upCase = '123456'.replace(/\d/g, i => ary[i - 1])
console.log('upCase', upCase) 
// upCase 一二三四五六
  1. \( 实现一个trim函数 \)
  • 直接去除空格,是我们比较常用的,直接将空字符替换.
    \s 匹配任何空白字符,包括空格、制表符、换页符等等
const trim = (str) => {
  return str.replace(/^\s*|\s*$/g, '')    
}
  • 提取非空空格法
const trim = (str) => {
  return str.replace(/^\s*(.*?)\s*$/g, '$1')    
}
  1. \( 数字价格千分位分割 \)
  • 将123456789变成123,456,789
'123456789'.replace(/(?!^)(?=(\d{3})+$)/g, ',') // 123,456,789
  1. \( 将字符串首字母转化为大写,剩下为小写 \)
const capitalize = (string) => {
  const capitalizeRegex = /(?:^|\s+)\w/g

  return string.toLowerCase().replace(capitalizeRegex, (match) => match.toUpperCase())
}
  1. \( 将字符串驼峰化 \)
const camelCase = (string) => {
  const camelCaseRegex = /[-_\s]+(.)?/g

  return string.replace(camelCaseRegex, (match, char) => {
    return char ? char.toUpperCase() : ''
  })
}
  1. \( 通过name获取url query参数 \)
const getQueryByName = (name) => {
  const queryNameRegex = new RegExp(`[?&]${name}=([^&]*)(&|$)`)
  const queryNameMatch = window.location.search.match(queryNameRegex)
  // 一般都会通过decodeURIComponent解码处理
  return queryNameMatch ? decodeURIComponent(queryNameMatch[1]) : ''
}
  1. \( 是否为中文 \)
const reg = /[\u4e00-\u9fa5]/

你可能感兴趣的:(javascript正则表达式)