当前位置:首页 >时尚 >20 个你应该掌握的强大而有用的正则表达式 我有另一种方式让我感到快乐

20 个你应该掌握的强大而有用的正则表达式 我有另一种方式让我感到快乐

2024-06-26 12:33:49 [百科] 来源:避面尹邢网

20 个你应该掌握的个应该掌强大而有用的正则表达式

作者:web前端开发 开发 前端 一起来了解下20 个你应该掌握的强大而有用的正则表达式都有哪些。

1.货币格式化

我经常需要在工作中使用到格式化的正则货币,使用正则表达式让这变得非常简单。表达

20 个你应该掌握的强大而有用的正则表达式 我有另一种方式让我感到快乐

const formatPrice = (price) => {   const regexp = new RegExp(`(?个应该掌!^)(?=(\\d{ 3})+${ price.includes('.') ? '\\.' : '$'})`, 'g')   return price.replace(regexp, ',')}formatPrice('123') // 123formatPrice('1234') // 1,234formatPrice('123456') // 123,456formatPrice('123456789') // 123,456,789formatPrice('123456789.123') // 123,456,789.123

你还有什么其他的方法吗?

20 个你应该掌握的强大而有用的正则表达式 我有另一种方式让我感到快乐

使用 Intl.NumberFormat 是我最喜欢的方式。

20 个你应该掌握的强大而有用的正则表达式 我有另一种方式让我感到快乐

const format = new Intl.NumberFormat('en-US',正则 {   style: 'currency',  currency: 'USD'})console.log(format.format(123456789.123)) // $123,456,789.12

修复它的方法不止一种!我有另一种方式让我感到快乐。表达

const amount = 1234567.89const formatter = new Intl.NumberFormat('en-US',个应该掌 {  style: 'currency', currency: 'USD' })console.log(formatter.format(amount)) // $1,234,567.89

我为什么要学习正则表达式?看起来好复杂!我失去了信心。正则

请放轻松,表达我的个应该掌朋友,您会看到正则表达式的正则魔力。

2.去除字符串空格的表达两种方法

如果我想从字符串中删除前导和尾随空格,我该怎么办?

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

防止 XSS 攻击的方法之一是进行 HTML 转义。转义规则如下,需要将对应的字符转换成等价的实体。而反转义就是将转义的实体转化为对应的字符

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 => fooBar2. foo-bar---- => fooBar3. 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')) // fooBarconsole.log(camelCase('foo-bar--')) // fooBarconsole.log(camelCase('foo_bar__')) // fooBar

6.将字符串首字母转为大写,其余转为小写

例如,“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 Worldconsole.log(capitalize('hello WORLD')) // Hello World

7、获取网页所有图片标签的图片地址

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=boyconsole.log(getQueryByName('name')) // fatfish// 2. name at the end// https://medium.com//?sex=boy&name=fatfishconsole.log(getQueryByName('name')) // fatfish// 2. name in the middle// https://medium.com//?sex=boy&name=fatfish&age=100console.log(getQueryByName('name')) // fatfish

9、匹配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')) // trueconsole.log(check24TimeRegexp.test('23:59')) // trueconsole.log(check24TimeRegexp.test('23:60')) // falseconsole.log(check24TimeRegexp.test('1:14')) // trueconsole.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')) // trueconsole.log(checkDateRegexp.test('2021/08/22')) // trueconsole.log(checkDateRegexp.test('2021.08.22')) // trueconsole.log(checkDateRegexp.test('2021.08/22')) // falseconsole.log(checkDateRegexp.test('2021/08-22')) // false

11.匹配十六进制颜色值

请从字符串中匹配颜色值,如#ffbbad、#FFF 十六进制

const matchColorRegex = /#(?:[\da-fA-F]{ 6}|[\da-fA-F]{ 3})/gconst colorString = '#12f3a1 #ffBabd #FFF #123 #586'console.log(colorString.match(matchColorRegex))// [ '#12f3a1', '#ffBabd', '#FFF', '#123', '#586' ]

12、检查URL前缀是否正确

检查 URL 是否以 http 或 https 开头

const checkProtocol = /^https?:/console.log(checkProtocol.test('https://juejin.cn/')) // trueconsole.log(checkProtocol.test('http://juejin.cn/')) // trueconsole.log(checkProtocol.test('//juejin.cn/')) // false

13.反串大小写

我们将反转字符串的大小写,例如,hello WORLD => HELLO world

const stringCaseReverseReg = /[a-z]/igconst string = 'hello WORLD'const string2 = string.replace(stringCaseReverseReg, (char) => {   const upperStr = char.toUpperCase()  return upperStr === char ? char.toLowerCase() : upperStr})console.log(string2) // HELLO world

14、windows下匹配文件夹和文件路径

const windowsPathRegex = /^[a-zA-Z]:\\(?:[^\\:*<>|"?\r\n/]+\\?)*(?:(?:[^\\:*<>|"?\r\n/]+)\.\w+)?$/console.log( windowsPathRegex.test("C:\\Documents\\Newsletters\\Summer2018.pdf") ) // trueconsole.log( windowsPathRegex.test("C:\\Documents\Newsletters\\") ) // trueconsole.log( windowsPathRegex.test("C:\\Documents\Newsletters") ) // trueconsole.log( windowsPathRegex.test("C:\\") ) // true

15.匹配id

请截取“<div id=”box”>hello world</div>”中的id

const matchIdRegexp = /id="([^"]*)"/console.log(`  <div id="box">    hello world  </div>`.match(matchIdRegexp)[1]) // box

16.判断版本是否正确

我们要求版本为 X.Y.Z 格式,其中 XYZ 都是至少一位数的数字

// x.y.zconst versionRegexp = /^(?:\d+\.){ 2}\d+$/console.log(versionRegexp.test('1.1.1')) // trueconsole.log(versionRegexp.test('1.000.1')) // trueconsole.log(versionRegexp.test('1.000.1.1')) // false

17.判断一个数是否为整数

const intRegex = /^[-+]?\d*$/const num1 = 12345console.log(intRegex.test(num1)) // trueconst num2 = 12345.1console.log(intRegex.test(num2)) // false

18.判断一个数是否为小数

const floatRegex = /^[-\+]?\d+(\.\d+)?$/const num = 1234.5console.log(floatRegex.test(num)) // true

19.判断一个字符串是否只包含字母

const letterRegex = /^[a-zA-Z]+$/const letterStr1 = 'fatfish'console.log(letterRegex.test(letterStr1)) // trueconst letterStr2 = 'fatfish_frontend'console.log(letterRegex.test(letterStr2)) // false

20.判断URL是否正确

const urlRegexp= /^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{ 2,6})([\/\w \.-]*)*\/?$/;console.log(urlRegexp.test("https://medium.com/")) // true

总结

以上就是我今天想与你分享的20个有关正则表达式的内容,希望对你有所帮助。

责任编辑:华轩 来源: 今日头条 字符串开发正则表达式

(责任编辑:综合)

    推荐文章
    热点阅读