检查字符串是否包含单词(不是子字符串)

chr*_*ong 1 javascript

我正在尝试检查字符串是否包含特定单词,而不仅仅是子字符串。

以下是一些示例输入/输出:

var str = "This is a cool area!";
containsWord(str, "is"); // return true
containsWord(str, "are"); // return false
containsWord(str, "area"); // return true
Run Code Online (Sandbox Code Playgroud)

以下函数将不起作用,因为对于第二种情况它也会返回 true:

function containsWord(haystack, needle) {
     return haystack.indexOf(needle) > -1;
}
Run Code Online (Sandbox Code Playgroud)

这也不起作用,因为它对于第三种情况返回 false:

function containsWord(haystack, needle) {
     return (' ' +haystack+ ' ').indexOf(' ' +needle+ ' ') > -1;
}
Run Code Online (Sandbox Code Playgroud)

那么如何检查字符串中是否包含单词呢?

xxx*_*tko 6

尝试使用正则表达式,其中\b元字符用于在单词的开头或结尾查找匹配项。

var str = "This is a cool area!";

function containsWord(str, word) {
  return str.match(new RegExp("\\b" + word + "\\b")) != null;
}

console.info(containsWord(str, "is")); // return true
console.info(containsWord(str, "are")); // return false
console.info(containsWord(str, "area")); // return true
Run Code Online (Sandbox Code Playgroud)