15 个常用的正则表达式技巧

开发 前端
你对正则表达式有何看法?我猜你会说这太晦涩难懂了,我对它根本不感兴趣。是的,我曾经和你一样,以为我这辈子都学不会了。

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

但我们不能否认它确实很强大,我在工作中经常使用它,今天,我总结了15个非常使用的技巧想与你一起来分享,同时也希望这对你有所帮助。

那么,我们现在就开始吧。

1. 格式化货币

我经常需要格式化货币,它需要遵循以下规则:

123456789 => 123,456,789

123456789.123 => 123,456,789.123

const formatMoney = (money) => {
  return money.replace(new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',')  
}


formatMoney('123456789') // '123,456,789'
formatMoney('123456789.123') // '123,456,789.123'
formatMoney('123') // '123'

您可以想象如果没有正则表达式我们将如何做到这一点?

2. Trim功能的两种实现方式

有时我们需要去除字符串的前导和尾随空格,使用正则表达式会非常方便,我想与大家分享至少两种方法。

方式1

const trim1 = (str) => {
  return str.replace(/^\s*|\s*$/g, '')    
}


const string = '   hello medium   '
const noSpaceString = 'hello medium'
const trimString = trim1(string)


console.log(string)
console.log(trimString, trimString === noSpaceString)
console.log(string)

太好了,我们已经删除了字符串“string”的前导和尾随空格。

方式2

const trim2 = (str) => {
  return str.replace(/^\s*(.*?)\s*$/g, '$1')    
}


const string = '   hello medium   '
const noSpaceString = 'hello medium'
const trimString = trim2(string)


console.log(string)
console.log(trimString, trimString === noSpaceString)
console.log(string)

通过第二种方式,我们也达到了目的。

3.解析链接上的搜索参数

你一定也经常需要从链接中获取参数吧?

// For example, there is such a link, I hope to get fatfish through getQueryByName('name')
// url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/home


const name = getQueryByName('name') // fatfish
const age = getQueryByName('age') // 100

使用正则表达式解决这个问题非常简单。

const getQueryByName = (name) => {
  const queryNameRegex = new RegExp(`[?&]${name}=([^&]*)(&|$)`)
  const queryNameMatch = window.location.search.match(queryNameRegex)
  // Generally, it will be decoded by decodeURIComponent
  return queryNameMatch ? decodeURIComponent(queryNameMatch[1]) : ''
}


const name = getQueryByName('name')
const age = getQueryByName('age')


console.log(name, age) // fatfish, 100

4. 驼峰式命名字符串

请将字符串转换为驼峰式大小写,如下所示:

1. foo Bar => fooBar
2. foo-bar---- => fooBar
3. foo_bar__ => fooBar

我的朋友们,没有什么比正则表达式更好的了。

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. 将字符串的第一个字母转换为大写

请将 hello world 转换为 Hello World。

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. 转义 HTML

防止 XSS 攻击的方法之一是进行 HTML 转义。 逃逸规则如下:

const escape = (string) => {
  const escapeMaps = {
    '&': 'amp',
    '<': 'lt',
    '>': 'gt',
    '"': 'quot',
    "'": '#39'
  }
  // The effect here is the same as that of /[&<> "']/g
  const escapeRegexp = new RegExp(`[${Object.keys(escapeMaps).join('')}]`, 'g')
  return string.replace(escapeRegexp, (match) => `&${escapeMaps[match]};`)
}


console.log(escape(`
  <div>
    <p>hello world</p>
  </div>
`))
/*
<div>
  <p>hello world</p>
</div>
*/

8. 取消转义 HTML

const unescape = (string) => {
  const unescapeMaps = {
    'amp': '&',
    'lt': '<',
    'gt': '>',
    'quot': '"',
    '#39': "'"
  }
  const unescapeRegexp = /&([^;]+);/g
  return string.replace(unescapeRegexp, (match, unescapeKey) => {
    return unescapeMaps[ unescapeKey ] || match
  })
}


console.log(unescape(`
  <div>
    <p>hello world</p>
  </div>
`))
/*
<div>
  <p>hello world</p>
</div>
*/

9. 24小时制比赛时间

请判断时间是否符合24小时制。 匹配规则如下:

01:14

1:14

1:1

23:59

const check24TimeRegexp = /^(?:(?:0?|1)\d|2[0-3]):(?:0?|[1-5])\d$/
console.log(check24TimeRegexp.test('01:14')) // true
console.log(check24TimeRegexp.test('23:59')) // true
console.log(check24TimeRegexp.test('23:60')) // false
console.log(check24TimeRegexp.test('1:14')) // true
console.log(check24TimeRegexp.test('1:1')) // true

10.匹配日期格式

请匹配日期格式,例如(yyyy-mm-dd、yyyy.mm.dd、yyyy/mm/dd),例如 2021–08–22、2021.08.22、2021/08/22。

const checkDateRegexp = /^\d{4}([-\.\/])(?:0[1-9]|1[0-2])\1(?:0[1-9]|[12]\d|3[01])$/


console.log(checkDateRegexp.test('2021-08-22')) // true
console.log(checkDateRegexp.test('2021/08/22')) // true
console.log(checkDateRegexp.test('2021.08.22')) // true
console.log(checkDateRegexp.test('2021.08/22')) // false
console.log(checkDateRegexp.test('2021/08-22')) // false

11. 匹配十六进制颜色值

请从字符串中获取十六进制颜色值。

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' ]

12. 检查URL的前缀是HTTPS还是HTTP

const checkProtocol = /^https?:/


console.log(checkProtocol.test('https://medium.com/')) // true
console.log(checkProtocol.test('http://medium.com/')) // true
console.log(checkProtocol.test('//medium.com/')) // false

13.请检查版本号是否正确

版本号必须采用 x.y.z 格式,其中 XYZ 至少为一位数字。

// x.y.z
const versionRegexp = /^(?:\d+\.){2}\d+$/


console.log(versionRegexp.test('1.1.1'))
console.log(versionRegexp.test('1.000.1'))
console.log(versionRegexp.test('1.000.1.1'))

14、获取网页上所有img标签的图片地址

const matchImgs = (sHtml) => {
  const imgUrlRegex = /<img[^>]+src="((?:https?:)?\/\/[^"]+)"[^>]*?>/gi
  let matchImgUrls = []


  sHtml.replace(imgUrlRegex, (match, $1) => {
    $1 && matchImgUrls.push($1)
  })
  return matchImgUrls
}


console.log(matchImgs(document.body.innerHTML))

15、按照3-4-4格式划分电话号码

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


console.log(mobile.replace(mobileReg, '-')) // 133-1234-5678



责任编辑:华轩 来源: web前端开发
相关推荐

2018-09-27 15:25:08

正则表达式前端

2015-12-07 10:03:40

实用PHP表达式

2010-03-01 15:51:59

Python则表达式

2009-06-24 11:24:23

JavaScript验正则表达式

2021-07-14 23:54:01

正则表达式数据

2020-09-04 09:16:04

Python正则表达式虚拟机

2019-10-29 09:20:48

Python文本正则表达式

2009-08-25 09:54:36

PHP正则表达式

2020-10-16 17:00:16

正则表达式字符Python

2011-11-23 11:04:41

BGPAS_PATH正则表达式

2009-06-09 09:00:09

java正则表达式

2019-04-30 11:15:51

正则表达式JS前端

2010-03-25 18:25:36

Python正则表达式

2009-09-16 17:15:57

正则表达式引擎

2016-11-10 16:21:22

Java 正则表达式

2023-09-13 08:12:45

2022-01-04 11:35:03

Linux Shel正则表达式Linux

2009-08-07 14:24:31

.NET正则表达式

2009-09-16 18:19:34

正则表达式组

2021-01-27 11:34:19

Python正则表达式字符串
点赞
收藏

51CTO技术栈公众号