前言:
正则表达式(Regular Expression)是一种强大的文本模式匹配工具,常用于字符串处理、数据验证、数据提取等领域。正则表达式由一系列字符组成,包括普通字符和元字符。普通字符表示字符串中的具体字符,如字母、数字、符号等;元字符则表示一种模式,用于匹配字符串中的特定模式。
今天我们就总结一下十个最常用的正则表达式。
1.货币格式化
我经常需要在工作中使用到格式化的货币,使用正则表达式让这变得非常简单。// 堆代码 duidaima.com const formatPrice = (price) => { const regexp = new RegExp(`(?!^)(?=(\\d{3})+${price.includes('.') ? '\\.' : '$'})`, 'g') return price.replace(regexp, ',') } formatPrice('123') // 123 formatPrice('1234') // 1,234 formatPrice('123456') // 123,456 formatPrice('123456789') // 123,456,789 formatPrice('123456789.123') // 123,456,789.123你还有什么其他的方法吗?使用 Intl.NumberFormat 是我最喜欢的方式。
const format = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) console.log(format.format(123456789.123)) // $123,456,789.12修复它的方法不止一种!我有另一种方式让我感到快乐。
const amount = 1234567.89 const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) console.log(formatter.format(amount)) // $1,234,567.89我为什么要学习正则表达式?看起来好复杂!我失去了信心。请放轻松,我的朋友,您会看到正则表达式的魔力。
console.log(' medium '.trim())这很简单,对吧?当然,使用正则表达式,我们至少有两种方法可以搞定。
const trim = (str) => { return str.replace(/^\s*|\s*$/g, '') } trim(' medium ') // 'medium'方案2
const trim = (str) => { return str.replace(/^\s*(.*?)\s*$/g, '$1') } trim(' medium ') // 'medium'3. 转义 HTML
// 堆代码 duidaima.com const escape = (string) => { const escapeMaps = { '&': 'amp', '<': 'lt', '>': 'gt', '"': 'quot', "'": '#39' } 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> */4. 未转义的 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> */5.驼峰化一个字符串
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__')) // fooBar6.将字符串首字母转为大写,其余转为小写
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
const matchImgs = (sHtml) => { const imgUrlRegex = /<img[^>]+src="((?:https?:)?\/\/[^"]+)"[^>]*?>/gi let matchImgUrls = [] sHtml.replace(imgUrlRegex, (match, $1) => { $1 && matchImgUrls.push($1) }) return matchImgUrls } matchImgs(document.body.innerHTML)8、通过名称获取url查询参数
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]) : '' } // 1. name in front // https://medium.com/?name=fatfish&sex=boy console.log(getQueryByName('name')) // fatfish // 2. name at the end // https://medium.com//?sex=boy&name=fatfish console.log(getQueryByName('name')) // fatfish // 2. name in the middle // https://medium.com//?sex=boy&name=fatfish&age=100 console.log(getQueryByName('name')) // fatfish9、匹配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')) // true10.匹配日期格式
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