我只想使用 javascript 搜索字符串中的特定单词。但是使用 match、indexOf 或 includes 无法正常工作。假设
let str = "Widget test";
if (~str.indexOf("Widge")) {
console.log( 'Found it!' );
}
它会打印找到它,因为它不匹配整个单词,只匹配子字符串。如果只有匹配项是 Widget,我如何将它返回到 found
但我想要的是:
如果输入字符串 = Widget,输出 = true
如果输入字符串 = Widge ,输出 = false
最佳答案
要准确匹配单词,您可以使用正则表达式。
/\bWidget\b/
将匹配整个单词。
在你的例子中:
let str = "Widget";
if (str.search(/\bWidget\b/) >= 0) {
console.log( 'Found it!' );
}
关于javascript - 如何在 JavaScript 中使用 indexOf 或 includes 只匹配确切的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54631048/