正則表達式在js前端的15個使用場景梳理總結(jié)
引言
正則什么的,你讓我寫,我會難受,你讓我用,真香!對于很多人來說寫正則就是”蘭德里的折磨“吧。如果不是有需求頻繁要用,根本就不會想著學它。(?!^)(?=(\\d{3})+
這種就跟外星文一樣。
但你要說是用它,它又真的好用。用來做做校驗、做做字符串提取、做做變形啥的,真不錯。最好的就是能 CV 過來直接用~
千分位格式化
在項目中經(jīng)常碰到關(guān)于貨幣金額的頁面顯示,為了讓金額的顯示更為人性化與規(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)雅的方法實現(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
通過正則,簡單就能實現(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 變量最佳是駝峰風格的寫法,怎樣將類似以下的其它聲明風格寫法轉(zhuǎn)化為駝峰寫法?
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
小寫轉(zhuǎn)大寫
這個需求常見,無需多言,用就完事兒啦:
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
實現(xiàn) trim()
trim() 方法用于刪除字符串的頭尾空白符,用正則可以模擬實現(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() 方法不會改變原始字符串,同樣,自定義實現(xiàn)的 trim1 也不會改變原始字符串;
HTML 轉(zhuǎn)義
防止 XSS 攻擊的方法之一是進行 HTML 轉(zhuǎn)義,符號對應(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> */
校驗 24 小時制
處理時間,經(jīng)常要用到正則,比如常見的:校驗時間格式是否是合法的 24 小時制:
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
校驗日期格式
常見的日期格式有:yyyy-mm-dd, yyyy.mm.dd, yyyy/mm/dd 這 3 種,如果有符號亂用的情況,比如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
匹配顏色值
在字符串內(nèi)匹配出 16 進制的顏色值:
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
這個需求也是很常見的,判斷請求協(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
校驗版本號
版本號必須采用 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'))
獲取網(wǎng)頁 img 地址
這個需求可能爬蟲用的比較多,用正則獲取當前網(wǎng)頁所有圖片的地址。在控制臺打印試試,太好用了~~
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))
格式化電話號碼
這個需求也是常見的一匹,用就完事了:
let mobile = '18379836654' let mobileReg = /(?=(\d{4})+$)/g console.log(mobile.replace(mobileReg, '-')) // 183-7983-6654
以上就是正則表達式在js前端的15個使用場景梳理總結(jié)的詳細內(nèi)容,更多關(guān)于js前端正則表達式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
json前后端數(shù)據(jù)交互相關(guān)代碼
本篇文章給大家分享了關(guān)于json前后端數(shù)據(jù)交互方法實現(xiàn)的相關(guān)知識點內(nèi)容,有興趣的讀者們可以參考學習下。2018-09-09JavaScript中instanceof與typeof運算符的用法及區(qū)別詳細解析
這篇文章主要是對JavaScript中instanceof與typeof運算符的用法及區(qū)別進行了詳細的分析介紹。需要的朋友可以過來參考下,希望對大家有所幫助2013-11-11Bootstrap Fileinput 4.4.7文件上傳實例詳解
這篇文章主要為大家詳細介紹了Bootstrap Fileinput 4.4.7文件上傳實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07動態(tài)創(chuàng)建按鈕的JavaScript代碼
本文給大家分享一段JS實例代碼介紹動態(tài)創(chuàng)建按鈕的方法,需要的朋友參考下本文2016-01-01JavaScript設(shè)計模式之職責鏈模式應(yīng)用示例
這篇文章主要介紹了JavaScript設(shè)計模式之職責鏈模式,結(jié)合實例形式分析了javascript責任鏈模式的概念、原理、使用方法及相關(guān)操作注意事項,需要的朋友可以參考下2018-08-08