我正在尝试使用includes()在字符串/句子中搜索确切的字符串/单词,并且我希望它返回true(如果确实如此)。但即使单词与更大单词的一部分匹配,我也会返回“true”。如何搜索完全匹配?我意识到includes()是区分大小写的,但我希望它对长度敏感,也就是说,我理解我可能应该以某种方式定义js字符串中的单词是什么,但不确定如何使用includes()来做到这一点。谢谢
var sentence = 'The quick brown fox jumps over the lazy dog.';
var word = 'own';
console.log(`The word "${word}" ${sentence.includes(word)? 'is' : 'is not'} in the sentence`);
// wanted output: "The word "own" is not in the sentence"
// real output: "The word "own" is in the sentence"
最佳答案
includes
尝试搜索与传递的字符串(参数)匹配的任何序列,在本例中,brown
中有 own
,因此它返回true,如果您希望仅在找到确切的单词 own
时才匹配,您可以使用 search
和 regex
,
var sentence = 'The quick brown fox jumps over the lazy dog.';
let wordFounder = word => {
let reg = new RegExp(`\\b${word}\\b`)
console.log(`The word "${word}" is ${sentence.search(reg) !== -1 ? '' : 'not'}
in the sentence`);
}
wordFounder("own")
wordFounder("brown")
关于javascript - 使用 String.includes() 在字符串中搜索精确的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57348671/