マスターすべき 20 の強力で便利な正規表現

「Big Front-end Private Kitchen」のWeChat公式アカウントをフォローし、パスワード[面接ガイド]を返信すると、フロントエンド面接の質問107ページを無料で受け取ることができます。

正規表現は、非常に強力な文字列パターン マッチング ツールです。一般的な正規表現をマスターすると、文字列操作とテキスト処理の効率が大幅に向上します。

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. 文字列からスペースを削除する 2 つの方法

文字列から先頭と末尾のスペースを削除したい場合はどうすればよいですか?

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

シンプルですよね?もちろん、正規表現を使用すると、少なくとも 2 つの方法があります。

オプション 1

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 攻撃を防ぐ 1 つの方法は、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>
`))
/*
&lt;div&gt;
  &lt;p&gt;hello world&lt;/p&gt;
&lt;/div&gt;
*/

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(`
  &lt;div&gt;
    &lt;p&gt;hello world&lt;/p&gt;
  &lt;/div&gt;
`))
/*
<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. Web ページ上のすべてのイメージ タグのイメージ アドレスを取得します。

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. 16 進数のカラー値を一致させる

#ffbbad、#FFF hex などの文字列の色の値と一致してください。

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. バージョンが正しいかどうかを確認します

バージョンは XYZ 形式である必要があります。XYZ は少なくとも 1 桁の数字です。

// 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 の正規表現をマスターすると、文字列の検証、置換、抽出という一般的なタスクを迅速に完了することができます。正規表現をプログラミング言語と組み合わせると、さまざまな文字列操作を実行するための強力なツールとなるため、時間をかけて習得して使用する価値があります。

 

おすすめ

転載: blog.csdn.net/weixin_41692221/article/details/131285761