Viki 写东西的地方


Advanced Usage of JavaScript Regular Expressions

1. Lazy Matching

For example, Hi+? will only match Hi in Hiiiii.

'Hiii'.replace(/Hi+?/, 'x') // xii
'Hiii'.replace(/Hi+/, 'x') // x

'Hellollo'.replace(/H.*?llo/, 'x') // xllo
'Hellollo'.replace(/H.*llo/, 'x') // x

'yoooooo'.replace(/yo{2,6}?/, 'x') // xoooo
'yoooooo'.replace(/yo{2,6}/, 'x') // x

2. Word Boundaries

'How are you?'.replace(/\b.+?\b/, 'x') // x are you?

3. Capturing Group Reference

Capturing group format: (xxx), backreference: \n, such as: \1, \2, etc.

'How are you?'.replace(/(how)/i, '$1 old') // How old are you?
'1#2#3'.replace(/^(\d)#(\d)#(\d)$/i, '$1 $2 $3') // 1 2 3
'111#111#111'.replace(/^(\d+)#\1#\1$/i, '$1') // 111

4. Named Capturing Group + Backreference

Named capturing group: (?<name>xxx), backreference: \k<name>

'111#111'.replace(/^(?<num>\d+)#\k<num>$/i, '$<num>') // 111

5. Lookahead and Lookbehind


  • Positive lookahead: (?=xx)
  • Negative lookahead: (?!xx), negative means cannot match
  • Positive lookbehind: (?<=xx)
  • Negative lookbehind: (?<!xx), negative means cannot match

6. Modifiers

In addition to the commonly used g for global matching and i for case-insensitive matching:

  • m: multiline shorthand, enables multiline matching, treats ^ and $ as the start and end of lines.
  • u: unicode shorthand, allows the use of Unicode code point escapes.
  • y: sticky shorthand, enables sticky matching, attempts to match from the last match position.

7. Second Argument of replace

If it is a string, you can use the following special characters:

  • $n: 1<=n<=99, matches the text captured by the 1st to 99th group.
  • $&: The matched substring.
  • `$``: The portion of the string that precedes the matched substring.
  • $': The portion of the string that follows the matched substring.
  • $$: The dollar sign.
  • $<name>: The result value of the named capturing group.

If it is a function, the return value of the function is used as the replacement string. The function follows the following rules:

  • The first argument is the matched substring, corresponding to $& mentioned above.
  • The 2nd to n+1th arguments correspond to the 1st to nth capturing group (if any).
  • The n+2th argument is the offset, the offset of the matched substring in the original string.
  • The n+3th argument is the original string being matched.
  • The n+4th argument is the object that matches the named capturing group.


Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.