正則表達(dá)式在js前端的15個(gè)使用場(chǎng)景梳理總結(jié)
引言
正則什么的,你讓我寫(xiě),我會(huì)難受,你讓我用,真香!對(duì)于很多人來(lái)說(shuō)寫(xiě)正則就是”蘭德里的折磨“吧。如果不是有需求頻繁要用,根本就不會(huì)想著學(xué)它。(?!^)(?=(\\d{3})+ 這種就跟外星文一樣。
但你要說(shuō)是用它,它又真的好用。用來(lái)做做校驗(yàn)、做做字符串提取、做做變形啥的,真不錯(cuò)。最好的就是能 CV 過(guò)來(lái)直接用~
千分位格式化
在項(xiàng)目中經(jīng)常碰到關(guān)于貨幣金額的頁(yè)面顯示,為了讓金額的顯示更為人性化與規(guī)范化,需要加入貨幣格式化策略。也就是所謂的數(shù)字千分位格式化。
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'
想想如果不是用正則,還可以用什么更優(yōu)雅的方法實(shí)現(xiàn)它?
解析鏈接參數(shù)
你一定常常遇到這樣的需求,要拿到 url 的參數(shù)的值,像這樣:
// 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
通過(guò)正則,簡(jiǎn)單就能實(shí)現(xiàn) getQueryByName 函數(shù):
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
駝峰字符串
JS 變量最佳是駝峰風(fēng)格的寫(xiě)法,怎樣將類似以下的其它聲明風(fēng)格寫(xiě)法轉(zhuǎn)化為駝峰寫(xiě)法?
1. foo Bar => fooBar
2. foo-bar---- => fooBar
3. foo_bar__ => fooBar
正則表達(dá)式分分鐘教做人:
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
小寫(xiě)轉(zhuǎn)大寫(xiě)
這個(gè)需求常見(jiàn),無(wú)需多言,用就完事兒啦:
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
實(shí)現(xiàn) trim()
trim() 方法用于刪除字符串的頭尾空白符,用正則可以模擬實(shí)現(xiàn) trim:
const trim1 = (str) => {
return str.replace(/^\s*|\s*$/g, '') // 或者 str.replace(/^\s*(.*?)\s*$/g, '$1')
}
const string = ' hello medium '
const noSpaceString = 'hello medium'
const trimString = trim1(string)
console.log(string)
console.log(trimString, trimString === noSpaceString) // hello medium true
console.log(string)
trim() 方法不會(huì)改變?cè)甲址瑯?,自定義實(shí)現(xiàn)的 trim1 也不會(huì)改變?cè)甲址?/p>
HTML 轉(zhuǎn)義
防止 XSS 攻擊的方法之一是進(jìn)行 HTML 轉(zhuǎn)義,符號(hào)對(duì)應(yīng)的轉(zhuǎn)義字符:
正則處理如下:
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>
*/
HTML 反轉(zhuǎn)義
有了正向的轉(zhuǎn)義,就有反向的逆轉(zhuǎn)義,操作如下:
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>
*/
校驗(yàn) 24 小時(shí)制
處理時(shí)間,經(jīng)常要用到正則,比如常見(jiàn)的:校驗(yàn)時(shí)間格式是否是合法的 24 小時(shí)制:
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
校驗(yàn)日期格式
常見(jiàn)的日期格式有:yyyy-mm-dd, yyyy.mm.dd, yyyy/mm/dd 這 3 種,如果有符號(hào)亂用的情況,比如2021.08/22,這樣就不是合法的日期格式,我們可以通過(guò)正則來(lái)校驗(yàn)判斷:
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
匹配顏色值
在字符串內(nèi)匹配出 16 進(jìn)制的顏色值:
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' ]
判斷 HTTPS/HTTP
這個(gè)需求也是很常見(jiàn)的,判斷請(qǐng)求協(xié)議是否是 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
校驗(yàn)版本號(hào)
版本號(hào)必須采用 x.y.z 格式,其中 XYZ 至少為一位,我們可以用正則來(lái)校驗(yàn):
// 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'))
獲取網(wǎng)頁(yè) img 地址
這個(gè)需求可能爬蟲(chóng)用的比較多,用正則獲取當(dāng)前網(wǎng)頁(yè)所有圖片的地址。在控制臺(tái)打印試試,太好用了~~
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))
格式化電話號(hào)碼
這個(gè)需求也是常見(jiàn)的一匹,用就完事了:
let mobile = '18379836654'
let mobileReg = /(?=(\d{4})+$)/g
console.log(mobile.replace(mobileReg, '-')) // 183-7983-6654
以上就是正則表達(dá)式在js前端的15個(gè)使用場(chǎng)景梳理總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于js前端正則表達(dá)式的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
小程序?qū)崿F(xiàn)倒計(jì)時(shí)組件的使用示例
倒計(jì)時(shí)是指從一個(gè)固定的時(shí)間開(kāi)始,向前推算一段時(shí)間,來(lái)計(jì)算目標(biāo)時(shí)間或剩余時(shí)間的過(guò)程,本文主要介紹了小程序?qū)崿F(xiàn)倒計(jì)時(shí)組件的使用示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09
JS實(shí)現(xiàn)網(wǎng)頁(yè)Div層Clone拖拽效果
這篇文章主要介紹了JS實(shí)現(xiàn)網(wǎng)頁(yè)Div層Clone拖拽效果,涉及JavaScript響應(yīng)鼠標(biāo)事件動(dòng)態(tài)改變頁(yè)面元素位置屬性及層級(jí)屬性的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09
javascript實(shí)現(xiàn)根據(jù)時(shí)間段顯示問(wèn)候語(yǔ)的方法
這篇文章主要介紹了javascript實(shí)現(xiàn)根據(jù)時(shí)間段顯示問(wèn)候語(yǔ)的方法,涉及javascript時(shí)間與字符串的相關(guān)操作技巧,需要的朋友可以參考下2015-06-06
javascript實(shí)現(xiàn)點(diǎn)擊后變換按鈕顯示文字的方法
這篇文章主要介紹了javascript實(shí)現(xiàn)點(diǎn)擊后變換按鈕顯示文字的方法,可實(shí)現(xiàn)顯示一些按鈕如果點(diǎn)擊了,按鈕文本變?yōu)椤包c(diǎn)了”,其他按鈕文本變?yōu)椤皼](méi)點(diǎn)”的效果,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-05-05
JavaScript數(shù)據(jù)結(jié)構(gòu)常見(jiàn)面試問(wèn)題整理
在JavaScript中,數(shù)據(jù)結(jié)構(gòu)是指相互之間存在一種或多種特定關(guān)系的數(shù)據(jù)元素的集合,是帶有結(jié)構(gòu)特性的數(shù)據(jù)元素的集合。常用的數(shù)據(jù)結(jié)構(gòu)有:數(shù)組、列表、棧、隊(duì)列、鏈表、字典、集合等等2022-08-08
通過(guò)隱藏iframe實(shí)現(xiàn)無(wú)刷新上傳文件操作
本文給大家介紹iframe無(wú)刷新上傳文件,通過(guò)一個(gè)隱藏的iframe來(lái)處理上傳操作我采用的是ReactJS,amazeui,nodejs1.html target指向iframe的name,就是把上傳后的操作交給iframe來(lái)處理2016-03-03
js RuntimeObject() 獲取ie里面自定義函數(shù)或者屬性的集合
取得ie 里面 自定義函數(shù)或者屬性的集合 使用RuntimeObject()實(shí)現(xiàn),需要的朋友可以參考下。2010-11-11

