自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

20 個(gè)你應(yīng)該掌握的強(qiáng)大而有用的正則表達(dá)式

開(kāi)發(fā) 前端
一起來(lái)了解下20 個(gè)你應(yīng)該掌握的強(qiáng)大而有用的正則表達(dá)式都有哪些。

1.貨幣格式化

我經(jīng)常需要在工作中使用到格式化的貨幣,使用正則表達(dá)式讓這變得非常簡(jiǎn)單。

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

修復(fù)它的方法不止一種!我有另一種方式讓我感到快樂(lè)。

const amount = 1234567.89
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })


console.log(formatter.format(amount)) // $1,234,567.89

我為什么要學(xué)習(xí)正則表達(dá)式?看起來(lái)好復(fù)雜!我失去了信心。

請(qǐng)放輕松,我的朋友,您會(huì)看到正則表達(dá)式的魔力。

2.去除字符串空格的兩種方法

如果我想從字符串中刪除前導(dǎo)和尾隨空格,我該怎么辦?

console.log('   medium   '.trim())

這很簡(jiǎn)單,對(duì)吧?當(dāng)然,使用正則表達(dá)式,我們至少有兩種方法可以搞定。

方案一

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. 轉(zhuǎn)義 HTML

防止 XSS 攻擊的方法之一是進(jìn)行 HTML 轉(zhuǎn)義。轉(zhuǎn)義規(guī)則如下,需要將對(duì)應(yīng)的字符轉(zhuǎn)換成等價(jià)的實(shí)體。而反轉(zhuǎn)義就是將轉(zhuǎn)義的實(shí)體轉(zhuǎn)化為對(duì)應(yīng)的字符

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. 未轉(zhuǎn)義的 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.駝峰化一個(gè)字符串

如下規(guī)則:把對(duì)應(yīng)的字符串變成駝峰的寫(xiě)法

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

6.將字符串首字母轉(zhuǎn)為大寫(xiě),其余轉(zhuǎn)為小寫(xiě)

例如,“hello world”轉(zhuǎn)換為“Hello World”

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

7、獲取網(wǎng)頁(yè)所有圖片標(biāo)簽的圖片地址

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、通過(guò)名稱(chēng)獲取url查詢(xún)參數(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]) : ''
}
// 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')) // fatfish

9、匹配24小時(shí)制時(shí)間

判斷時(shí)間是否符合24小時(shí)制。 

匹配規(guī)則如下:

  • 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')) // 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')) // 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

11.匹配十六進(jìn)制顏色值

請(qǐng)從字符串中匹配顏色值,如#ffbbad、#FFF 十六進(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' ]

12、檢查URL前綴是否正確

檢查 URL 是否以 http 或 https 開(kāi)頭

const checkProtocol = /^https?:/


console.log(checkProtocol.test('https://juejin.cn/')) // true
console.log(checkProtocol.test('http://juejin.cn/')) // true
console.log(checkProtocol.test('//juejin.cn/')) // false

13.反串大小寫(xiě)

我們將反轉(zhuǎn)字符串的大小寫(xiě),例如,hello WORLD => HELLO world

const stringCaseReverseReg = /[a-z]/ig
const 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") ) // true


console.log( windowsPathRegex.test("C:\\Documents\Newsletters\\") ) // true
console.log( windowsPathRegex.test("C:\\Documents\Newsletters") ) // true
console.log( windowsPathRegex.test("C:\\") ) // true

15.匹配id

請(qǐng)截取“<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 都是至少一位數(shù)的數(shù)字

// x.y.z
const versionRegexp = /^(?:\d+\.){2}\d+$/


console.log(versionRegexp.test('1.1.1')) // true
console.log(versionRegexp.test('1.000.1')) // true
console.log(versionRegexp.test('1.000.1.1')) // false

17.判斷一個(gè)數(shù)是否為整數(shù)

const intRegex = /^[-+]?\d*$/


const num1 = 12345
console.log(intRegex.test(num1)) // true
const num2 = 12345.1
console.log(intRegex.test(num2)) // false

18.判斷一個(gè)數(shù)是否為小數(shù)

const floatRegex = /^[-\+]?\d+(\.\d+)?$/


const num = 1234.5
console.log(floatRegex.test(num)) // true

19.判斷一個(gè)字符串是否只包含字母

const letterRegex = /^[a-zA-Z]+$/


const letterStr1 = 'fatfish'
console.log(letterRegex.test(letterStr1)) // true
const 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

總結(jié)

以上就是我今天想與你分享的20個(gè)有關(guān)正則表達(dá)式的內(nèi)容,希望對(duì)你有所幫助。

責(zé)任編輯:華軒 來(lái)源: 今日頭條
相關(guān)推薦

2016-12-19 10:22:05

代碼正則表達(dá)式

2019-05-21 10:42:41

Python正則表達(dá)式

2018-09-27 15:25:08

正則表達(dá)式前端

2024-09-14 09:18:14

Python正則表達(dá)式

2016-09-12 09:57:08

grep命令表達(dá)式Linux

2015-12-07 10:03:40

實(shí)用PHP表達(dá)式

2023-09-04 15:52:07

2020-09-04 09:16:04

Python正則表達(dá)式虛擬機(jī)

2009-08-07 14:24:31

.NET正則表達(dá)式

2020-09-18 06:42:14

正則表達(dá)式程序

2018-08-21 11:00:20

前端正則表達(dá)式Java

2021-03-02 07:33:13

開(kāi)發(fā)C#字符

2010-03-25 18:25:36

Python正則表達(dá)式

2009-09-16 15:45:56

email的正則表達(dá)式

2019-11-29 16:25:00

前端正則表達(dá)式字符串

2009-06-09 09:16:52

Java正則表達(dá)式

2020-11-04 09:23:57

Python

2021-01-27 11:34:19

Python正則表達(dá)式字符串

2009-02-18 09:48:20

正則表達(dá)式Java教程

2009-09-16 18:19:34

正則表達(dá)式組
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)