欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

正則表達式在js前端的15個使用場景梳理總結(jié)

 更新時間:2022年07月08日 09:57:54   作者:掘金安東尼  
本篇帶來15個正則使用場景,按需索取,收藏恒等于學會?。∮行枰呐笥芽梢越梃b參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

引言

正則什么的,你讓我寫,我會難受,你讓我用,真香!對于很多人來說寫正則就是”蘭德里的折磨“吧。如果不是有需求頻繁要用,根本就不會想著學它。(?!^)(?=(\\d{3})+ 這種就跟外星文一樣。

但你要說是用它,它又真的好用。用來做做校驗、做做字符串提取、做做變形啥的,真不錯。最好的就是能 CV 過來直接用~

千分位格式化

在項目中經(jīng)常碰到關(guān)于貨幣金額的頁面顯示,為了讓金額的顯示更為人性化與規(guī)范化,需要加入貨幣格式化策略。也就是所謂的數(shù)字千分位格式化。

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'

想想如果不是用正則,還可以用什么更優(yōu)雅的方法實現(xiàn)它?

解析鏈接參數(shù)

你一定常常遇到這樣的需求,要拿到 url 的參數(shù)的值,像這樣:

// 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

通過正則,簡單就能實現(xiàn) getQueryByName 函數(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]) : ''
}
const name = getQueryByName('name')
const age = getQueryByName('age')
console.log(name, age) // fatfish, 100

駝峰字符串

JS 變量最佳是駝峰風格的寫法,怎樣將類似以下的其它聲明風格寫法轉(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

小寫轉(zhuǎn)大寫

這個需求常見,無需多言,用就完事兒啦:

const capitalize = (string) =&gt; {
  const capitalizeRegex = /(?:^|\s+)\w/g
  return string.toLowerCase().replace(capitalizeRegex, (match) =&gt; match.toUpperCase())
}
console.log(capitalize('hello world')) // Hello World
console.log(capitalize('hello WORLD')) // Hello World

實現(xiàn) trim()

trim() 方法用于刪除字符串的頭尾空白符,用正則可以模擬實現(xiàn) trim:

const trim1 = (str) => {
  return str.replace(/^\s*|\s*$/g, '') // 或者 str.replace(/^\s*(.*?)\s*$/g, '$1')
}
const string = '   hello medium   '
const noSpaceString = 'hello medium'
const trimString = trim1(string)
console.log(string)
console.log(trimString, trimString === noSpaceString) // hello medium true
console.log(string)

trim() 方法不會改變原始字符串,同樣,自定義實現(xiàn)的 trim1 也不會改變原始字符串;

HTML 轉(zhuǎn)義

防止 XSS 攻擊的方法之一是進行 HTML 轉(zhuǎn)義,符號對應(yīng)的轉(zhuǎn)義字符:

正則處理如下:

const escape = (string) => {
  const escapeMaps = {
    '&': 'amp',
    '<': 'lt',
    '>': 'gt',
    '"': 'quot',
    "'": '#39'
  }
  // The effect here is the same as that of /[&amp;<> "']/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>
`))
/*
&lt;div&gt;
  &lt;p&gt;hello world&lt;/p&gt;
&lt;/div&gt;
*/

HTML 反轉(zhuǎn)義

有了正向的轉(zhuǎn)義,就有反向的逆轉(zhuǎn)義,操作如下:

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(`
  &lt;div&gt;
    &lt;p&gt;hello world&lt;/p&gt;
  &lt;/div&gt;
`))
/*
<div>
  <p>hello world</p>
</div>
*/

校驗 24 小時制

處理時間,經(jīng)常要用到正則,比如常見的:校驗時間格式是否是合法的 24 小時制:

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

校驗日期格式

常見的日期格式有:yyyy-mm-dd, yyyy.mm.dd, yyyy/mm/dd 這 3 種,如果有符號亂用的情況,比如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

匹配顏色值

在字符串內(nèi)匹配出 16 進制的顏色值:

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' ]

判斷 HTTPS/HTTP

這個需求也是很常見的,判斷請求協(xié)議是否是 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

校驗版本號

版本號必須采用 x.y.z 格式,其中 XYZ 至少為一位,我們可以用正則來校驗:

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

獲取網(wǎng)頁 img 地址

這個需求可能爬蟲用的比較多,用正則獲取當前網(wǎng)頁所有圖片的地址。在控制臺打印試試,太好用了~~

const matchImgs = (sHtml) =&gt; {
  const imgUrlRegex = /&lt;img[^&gt;]+src="((?:https?:)?\/\/[^"]+)"[^&gt;]*?&gt;/gi
  let matchImgUrls = []
  sHtml.replace(imgUrlRegex, (match, $1) =&gt; {
    $1 &amp;&amp; matchImgUrls.push($1)
  })
  return matchImgUrls
}
console.log(matchImgs(document.body.innerHTML))

格式化電話號碼

這個需求也是常見的一匹,用就完事了:

let mobile = '18379836654' 
let mobileReg = /(?=(\d{4})+$)/g 
console.log(mobile.replace(mobileReg, '-')) // 183-7983-6654

以上就是正則表達式在js前端的15個使用場景梳理總結(jié)的詳細內(nèi)容,更多關(guān)于js前端正則表達式的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論