在项目中常用的正则表达式

 

前言

如何看待正则表达式?我猜你会说它太晦涩难懂,我对它根本不感兴趣。是的,我曾经和你一样,认为我这辈子都学不会。

但我们不能否认它真的很强大,所以我寻了 8 个小窍门与大家分享

 

 

1. 格式化货币  : new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g')

 

 

 

 2. trim功能:/^\s*|\s*$/g 或者 /^\s*(.*?)\s*$/g

 

 

 

3.解析url上的参数:new RegExp(`[?&]${name}=([^&]*)(&|$)`) 

 

   然后   window.location.search.match(  *** 正则***  )

 

 

 

 

 

4. 驼峰式字符串:/[-_\s]+(.)?/g

const camelCase = (string) => {
  const camelCaseRegex = /[-_\s]+(.)?/g
  return string.replace(camelCaseRegex, (match, char) => {
    return char ? char.toUpperCase() : ''
  })
}

console.log(camelCase('foo Bar')) // fooBar
console.log(camelCase('foo-bar--')) // fooBar
console.log(camelCase('foo_bar__')) // fooBar

 

 

 

 

 5. 字符串的首字母转换为大写:/(?:^|\s+)\w/g

const capitalize = (string) => {
  const capitalizeRegex = /(?:^|\s+)\w/g
  return string.toLowerCase().replace(capitalizeRegex, (match) => match.toUpperCase())
}

console.log(capitalize('hello world')) // Hello World
console.log(capitalize('hello WORLD')) // Hello World

6. Escape HTML(HTML 转义防止XSS 攻击):new RegExp(`[${Object.keys(escapeMaps).join('')}]`, 'g')

 

 

 

7. 十六进制匹配颜色值:/#(?:[\da-fA-F]{6}|[\da-fA-F]{3})/g

const matchColorRegex = /#(?:[\da-fA-F]{6}|[\da-fA-F]{3})/g
const colorString = '#12f3a1 #ffBabd #FFF #123 #586'

console.log(colorString.match(matchColorRegex))
// [ '#12f3a1', '#ffBabd', '#FFF', '#123', '#586' ]

 

8. 按照 3-4-4 格式划分电话号码:/(?=(\d{4})+$)/g

let mobile = '18379836654' 
let mobileReg = /(?=(\d{4})+$)/g 

console.log(mobile.replace(mobileReg, '-')) // 183-7983-6654

 

 

转载于:https://javascript.plainenglish.io/15-regular-expression-tricks-tips-for-you-bd7785c9a881

posted @ 2022-06-21 11:57  言之空  阅读(38)  评论(0编辑  收藏  举报