成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

20 個你應該掌握的強大而有用的正則表達式

開發 前端
一起來了解下20 個你應該掌握的強大而有用的正則表達式都有哪些。

1.貨幣格式化

我經常需要在工作中使用到格式化的貨幣,使用正則表達式讓這變得非常簡單。

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

我為什么要學習正則表達式?看起來好復雜!我失去了信心。

請放輕松,我的朋友,您會看到正則表達式的魔力。

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 => 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.將字符串首字母轉為大寫,其余轉為小寫

例如,“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 World
console.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=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小時制時間

判斷時間是否符合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')) // 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.匹配十六進制顏色值

請從字符串中匹配顏色值,如#ffbbad、#FFF 十六進制

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 開頭

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.反串大小寫

我們將反轉字符串的大小寫,例如,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

請截取“<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.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.判斷一個數是否為整數

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


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

18.判斷一個數是否為小數

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


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

19.判斷一個字符串是否只包含字母

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

總結

以上就是我今天想與你分享的20個有關正則表達式的內容,希望對你有所幫助。

責任編輯:華軒 來源: 今日頭條
相關推薦

2019-05-21 10:42:41

Python正則表達式

2016-12-19 10:22:05

代碼正則表達式

2018-09-27 15:25:08

正則表達式前端

2024-09-14 09:18:14

Python正則表達式

2016-09-12 09:57:08

grep命令表達式Linux

2020-09-04 09:16:04

Python正則表達式虛擬機

2023-09-04 15:52:07

2015-12-07 10:03:40

實用PHP表達式

2009-08-07 14:24:31

.NET正則表達式

2020-09-18 06:42:14

正則表達式程序

2018-08-21 11:00:20

前端正則表達式Java

2020-11-04 09:23:57

Python

2019-11-29 16:25:00

前端正則表達式字符串

2009-09-16 15:45:56

email的正則表達式

2009-06-09 09:16:52

Java正則表達式

2010-03-25 18:25:36

Python正則表達式

2021-03-02 07:33:13

開發C#字符

2017-05-12 10:47:45

Linux正則表達式程序基礎

2022-03-28 06:19:14

正則表達式開發

2021-01-27 11:34:19

Python正則表達式字符串
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 黑人巨大精品 | 中文久久 | 综合久 | www.国产| 日韩精品一区二区三区视频播放 | 亚洲欧美中文日韩在线v日本 | 亚洲va在线va天堂va狼色在线 | 国产成人久久精品一区二区三区 | 精品国产欧美一区二区三区成人 | 在线观看黄色 | 国产在线一区二区三区 | 国产高清自拍视频在线观看 | 久久久高清 | 久草免费在线视频 | 干干天天 | 色视频在线播放 | av电影一区 | 色久影院| 国产精品美女久久久久aⅴ国产馆 | 免费在线一区二区三区 | 中文字幕一区二区在线观看 | 电影午夜精品一区二区三区 | 日韩av网址在线观看 | 欧美 日韩 综合 | 国产精品久久久久久亚洲调教 | 在线观看免费高清av | 亚洲高清久久 | 久久久久久久av麻豆果冻 | 精品福利在线视频 | 成人性视频免费网站 | 日韩综合在线视频 | 亚洲日本成人 | 亚洲国产成人精品女人 | 欧美激情99 | 中文字幕在线三区 | 免费国产视频在线观看 | 黄色网址av| 国产精品久久久久久久久免费软件 | 欧美激情精品久久久久久变态 | 欧美精品区 | 精国产品一区二区三区 |