gpt4 book ai didi

javascript - 使用 String.includes() 在字符串中搜索确切的字符串

转载 作者:行者123 更新时间:2023-11-29 20:33:40 27 4
gpt4 key购买 nike

我正在尝试使用 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 因此它返回是的,如果您希望它仅在找到确切的单词 own 时匹配,您可以使用 searchregex

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com