我正在学习 JavaScript 中的正则表达式,我面临的问题是我试图理解为什么\b 元字符使用起来如此特别?我认为不使用它与使用它没有什么区别,那么使用它和不使用它有什么区别呢?这就是我的意思。
带有\b
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search for "W3" at the beginning or end of a word in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools";
var patt1 = /\bW3/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
没有\b
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search for "W3" at the beginning or end of a word in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools";
var patt1 = /W3/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
通过阅读它,我已经知道它的定义意味着什么,但我只是想问,如果它在上面两个代码示例中产生相同的结果,为什么还要使用它?如果有人可以向我展示 2 个代码示例来展示它们如何给出不同的结果,我将非常感激。我什至将火柴移到了中间,但它仍然给了我与不使用它相同的结果。
来源
最佳答案
你的两个例子都没有达到 html 声明的效果。前往https://www.regextester.com/并使用 blahW3blah
、W3blah
和 blahW3
作为测试字符串。您的正则表达式应该匹配最后两个,但不匹配第一个。
您需要:
(\bW3|W3\b)
(在单词开头匹配 W3 (\bW3
) 或 (|
) 在单词末尾匹配 W3 (W3\b
)
关于javascript - 使用\b 元字符与不使用它的结果相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48511264/