关于前端:15-个常用的正则表达式技巧

4次阅读

共计 4878 个字符,预计需要花费 13 分钟才能阅读完成。

你对正则表达式有何认识?我猜你会说这太艰涩难懂了,我对它基本不感兴趣。是的,我已经和你一样,认为我这辈子都学不会了。

但咱们不能否定它的确很弱小,我在工作中常常应用它,明天,我总结了 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’
您能够设想如果没有正则表达式咱们将如何做到这一点?

  1. 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=fa…

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

  1. 驼峰式命名字符串

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

  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

  1. 将字符串的第一个字母转换为大写

请将 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

  1. 本义 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>
*/

  1. 勾销本义 HTML

const unescape = (string) => {
const unescapeMaps = {

'amp': '&',
'lt': '<',
'gt': '>',
'quot': '"','#39':"'"

}
const unescapeRegexp = /&(1+);/g
return string.replace(unescapeRegexp, (match, unescapeKey) => {

return unescapeMaps[unescapeKey] || match

})
}

console.log(unescape(`
<div>

&lt;p&gt;hello world&lt;/p&gt;

</div>
`))
/*
<div>
<p>hello world</p>
</div>
*/

  1. 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

  1. 匹配十六进制色彩值

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

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

  1. 查看 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 = /<img2+src=”((?:https?:)?//3+)”2*?>/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
最初

感激你的浏览,期待您的关注和浏览更多优质文章。


  1. ; ↩
  2. > ↩
  3. ” ↩
正文完
 0