天天看點

14 種有用的 JavaScript 正則化方法

14 種有用的 JavaScript 正則化方法

英文 | https://blog.bitsrc.io/14-commonly-used-regularization-methods-b97db6956ac4

翻譯 | 楊小愛

1、千位格式

在項目中,經常會遇到關于貨币數量的頁面顯示。為了使金額的顯示更加人性化和标準化,需要添加貨币格式化,這就是所謂的千位數字格式。

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、解析URL參數

你一定經常會遇到這樣的需要擷取url的參數值,像這樣:

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

通過規律性,getQueryByName 函數可以很容易地實作:

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      

3、駝峰式字元串

JS 變量最好用 camelCase 編寫,讓我們看看如何編寫一個将其他大小寫格式轉換為 camelCase 的函數。

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      

4、小寫轉大寫

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      

5、實作trim()

trim() 方法用于去除字元串開頭和結尾的空格,trim 可以用正規表達式模拟:

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


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


console.log(string)
console.log(trimString, trimString === noSpaceString) // hello boy true
console.log(string)      

trim() 方法不會改變原始字元串,同樣,trim1 的自定義實作也不會改變原始字元串。

6、 HTML轉義

防止XSS攻擊的方法之一是進行HTML轉義,轉義符對應符号。

正常處理如下:

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

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

8、檢查 24 小時制

對于處理時間,經常使用規則的規則,比如常見的:檢查時間格式是不是合法的 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      

9、檢查日期格式

常見的日期格式有:yyyy-mm-dd、yyyy.mm.dd、yyyy/mm/dd。

如果出現亂用符号的情況,比如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      

10、比對顔色

比對字元串中的十六進制顔色值:

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

11、确定HTTPS/HTTP

這個要求也很常見,判斷請求協定是否為HTTPS/HTTP。

const checkProtocol = /^https?:/  console.log(checkProtocol.test('https://google.com/')) // true console.log(checkProtocol.test('http://google.com/')) // true console.log(checkProtocol.test('//google.com/')) // false      

12、檢查版本号

版本号必須是 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      

13、擷取網頁圖檔位址

這個需求可能更多被爬蟲使用,使用正則擷取目前網頁所有圖檔的位址。

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

14、格式化電話号碼

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

總結

以上就是我今天與你分享的14個關于JavaScript正則化的方法,希望這些方法對你有用,如果你覺得對你有幫助的話,請記得點贊我,關注我,并将其分享給你的朋友,也許能夠幫助到他。