正则表达式的解释

Mic*_*res 1 javascript regex jquery

我对正则表达式并不是很了解,我也没有完全理解这一点,我从中得到的是它找到每个h1并为它添加一个类的最后一个单词.

$("h1").html(function(index, old) {
    return old.replace(/(\b\w+)$/, '<span class="myClass">$1</span>');
});
Run Code Online (Sandbox Code Playgroud)

我正试图通过最后两个字符使它工作

Tot*_*oto 5

这是和解释:

/       : regex delimter
  (     : begin capture group #1
    \b  : word boundary
    \w+ : one or more word character (same as [a-zA-Z0-9_]+)
  )     : end of group
  $     : end of string
/       : regex delimiter
Run Code Online (Sandbox Code Playgroud)

它匹配字符串的最后一个单词,即h1标签的最后一个单词.

  • 我很难用初学者的眼睛看东西,但我不认为这个"解释"实际上解释了什么.告诉他_why_他需要`\ b`和所有这些东西(提示:他没有). (2认同)