javascript - 正则表达式返回整个单词匹配结果

标签 javascript

如何匹配整个单词?

<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a global search for "is" in a strisng.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "Is Alvin this all there is sis?";
    var patt1 = /is|alvin/gi;
    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 "is" in a strisng.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "Is Alvin this all there is sis?";
    var patt1 = /\b(?:is|alvin)\b/gi;
    var result = str.match(patt1);
    document.getElementById("demo").innerHTML = result;
}
</script>

</body>
</html>

关于javascript - 正则表达式返回整个单词匹配结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40778166/

相关文章:

javascript - 将鼠标悬停在图像上以在 JavaScript 中添加叠加层

漂亮的 html

javascript - 从外部域调整 iframe 高度

javascript - 我们可以使用 Between 来处理 JavaScript 数组的长度吗

javascript - 在 IE7 和 8 中使用 javascript 将内容动态添加到 UI 压缩下面的内容

javascript - Highcharts 不显示 csv 文件中的图表

javascript - 如何在图像上方动态生成DIV

javascript - 将额外的行附加到 jqueryui 自动完成(即使自动完成没有任何匹配项)

javascript - 如何使用map函数重新组装以下json?

javascript - Node JS 使用 windows % 变量视为相对路径的绝对路径