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

15 個常用的正則表達式技巧

開發(fā) 前端
你對正則表達式有何看法?我猜你會說這太晦澀難懂了,我對它根本不感興趣。是的,我曾經(jīng)和你一樣,以為我這輩子都學不會了。

你對正則表達式有何看法?我猜你會說這太晦澀難懂了,我對它根本不感興趣。是的,我曾經(jīng)和你一樣,以為我這輩子都學不會了。

但我們不能否認它確實很強大,我在工作中經(jīng)常使用它,今天,我總結(jié)了15個非常使用的技巧想與你一起來分享,同時也希望這對你有所幫助。

那么,我們現(xiàn)在就開始吧。

1. 格式化貨幣

我經(jīng)常需要格式化貨幣,它需要遵循以下規(guī)則:

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'

您可以想象如果沒有正則表達式我們將如何做到這一點?

2. Trim功能的兩種實現(xiàn)方式

有時我們需要去除字符串的前導和尾隨空格,使用正則表達式會非常方便,我想與大家分享至少兩種方法。

方式1

const trim1 = (str) => {
  return str.replace(/^\s*|\s*$/g, '')    
}


const string = '   hello medium   '
const noSpaceString = 'hello medium'
const trimString = trim1(string)


console.log(string)
console.log(trimString, trimString === noSpaceString)
console.log(string)

太好了,我們已經(jīng)刪除了字符串“string”的前導和尾隨空格。

方式2

const trim2 = (str) => {
  return str.replace(/^\s*(.*?)\s*$/g, '$1')    
}


const string = '   hello medium   '
const noSpaceString = 'hello medium'
const trimString = trim2(string)


console.log(string)
console.log(trimString, trimString === noSpaceString)
console.log(string)

通過第二種方式,我們也達到了目的。

3.解析鏈接上的搜索參數(shù)

你一定也經(jīng)常需要從鏈接中獲取參數(shù)吧?

// For example, there is such a link, I hope to get fatfish through getQueryByName('name')
// 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

4. 駝峰式命名字符串

請將字符串轉(zhuǎn)換為駝峰式大小寫,如下所示:

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

5. 將字符串的第一個字母轉(zhuǎn)換為大寫

請將 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

6. 轉(zhuǎn)義 HTML

防止 XSS 攻擊的方法之一是進行 HTML 轉(zhuǎn)義。 逃逸規(guī)則如下:

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>
`))
/*
<div>
  <p>hello world</p>
</div>
*/

8. 取消轉(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>
*/

9. 24小時制比賽時間

請判斷時間是否符合24小時制。 匹配規(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. 匹配十六進制顏色值

請從字符串中獲取十六進制顏色值。

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的前綴是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

13.請檢查版本號是否正確

版本號必須采用 x.y.z 格式,其中 XYZ 至少為一位數(shù)字。

// x.y.z
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'))

14、獲取網(wǎng)頁上所有img標簽的圖片地址

const matchImgs = (sHtml) => {
  const imgUrlRegex = /<img[^>]+src="((?:https?:)?\/\/[^"]+)"[^>]*?>/gi
  let matchImgUrls = []


  sHtml.replace(imgUrlRegex, (match, $1) => {
    $1 && matchImgUrls.push($1)
  })
  return matchImgUrls
}


console.log(matchImgs(document.body.innerHTML))

15、按照3-4-4格式劃分電話號碼

let mobile = '13312345678' 
let mobileReg = /(?=(\d{4})+$)/g 


console.log(mobile.replace(mobileReg, '-')) // 133-1234-5678



責任編輯:華軒 來源: web前端開發(fā)
相關(guān)推薦

2015-12-07 10:03:40

實用PHP表達式

2018-09-27 15:25:08

正則表達式前端

2009-06-24 11:24:23

JavaScript驗正則表達式

2010-03-01 15:51:59

Python則表達式

2024-09-14 09:18:14

Python正則表達式

2019-10-29 09:20:48

Python文本正則表達式

2021-07-14 23:54:01

正則表達式數(shù)據(jù)

2009-08-25 09:54:36

PHP正則表達式

2011-11-23 11:04:41

BGPAS_PATH正則表達式

2009-06-09 09:00:09

java正則表達式

2020-09-04 09:16:04

Python正則表達式虛擬機

2020-10-16 17:00:16

正則表達式字符Python

2016-11-10 16:21:22

Java 正則表達式

2022-01-04 11:35:03

Linux Shel正則表達式Linux

2023-09-13 08:12:45

2009-09-16 17:15:57

正則表達式引擎

2019-04-30 11:15:51

正則表達式JS前端

2024-10-07 09:26:18

2010-03-25 18:25:36

Python正則表達式

2009-08-07 14:24:31

.NET正則表達式
點贊
收藏

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