我要检查字符串是否确实包含特定单词。像这样
"word"
字符串包含"word"
字,与;;
"daword"
字符串包含"word"
字,与;;
"dawordo"
字符串包含"word"
个单词。
"word"
字符串应实际上包含"word"
字,与;
"(whitespaces)word(whitespaces)"
字符串应实际上包含"word"
字,与;
"da word"
字符串应真正包含"word"
字样;
"da word o"
字符串应真正包含"word"
字样;
"(white spaces)word"
字符串应真正包含"word"
字样;
"word(white spaces)"
字符串应真正包含"word"
字样;
如何在JavaScript中执行此操作?谢谢!
答案 0 :(得分:2)
正则表达式\bword\b
可以解决问题。
// should use \b with regex
var str = 'testwordtest';
if(str.match(/\bword\b/)){
console.log('match');
} else {
console.log('no match');
}
答案 1 :(得分:0)
String.includes
const target = 'word';
const arr = ['word', ' word ', 'hello_word', 'not_here'];
arr.forEach(w => console.log(w, w.includes(target)));
答案 2 :(得分:-1)
您可以使用indexof函数。如果句子中不包含您要查找的单词,则返回-1,否则将返回偏移量。
https://www.w3schools.com/jsref/jsref_indexof.asp
如果您不希望区分大小写,我建议稍微修改一下示例以首先将字符串转换为小写。
var str = "Hello world, Welcome to the universe.";
var n = str.toLowerCase().indexOf("welcome");
if(n > -1)
{
console.log("The search string was located at offset " + n);
}
else
{
console.log("The string did not contain the search string...");
}