千分位格式化
在專案中經常碰到關于貨幣金額的頁面顯示,為了讓金額的顯示更為人性化與規范化,需要加入貨幣格式化策略,也就是所謂的數字千分位格式化,
例如 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'
決議鏈接引數
當獲取URL中的引數時候
// 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
通過正則,簡單就能實作 getQueryByName 函式:
駝峰字串
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
小寫轉大寫
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
實作 trim()
trim() 方法用于洗掉字串的頭尾空白符,用正則可以模擬實作 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
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> `))
校驗 24 小時制
處理時間,經常要用到正則,比如常見的:校驗時間格式是否是合法的 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
匹配顏色值
在字串內匹配出 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
這個需求也是很常見的,判斷請求協議是否是 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 至少為一位,我們可以用正則來校驗:
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'))
獲取網頁 img 地址
這個需求可能爬蟲用的比較多,用正則獲取當前網頁所有圖片的地址,在控制臺列印試試,太好用了~~
const matchImgs = (sHtml) => { const imgUrlRegex = /<img[^>]+src="https://www.cnblogs.com/qing1224/p/((?: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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/502739.html
標籤:JavaScript

