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

标签 javascript string

我正在尝试使用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 时才匹配,您可以使用 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/

相关文章:

c++ - 如何结合 C++ 字符串和 Arduino 字符串?

Java 正则表达式匹配不正确

javascript - 如何确定给定字符串是否经过 HTML 转义?

mysql - 使用Join时如何选择不同的记录?

javascript - ember-data:如何获取嵌入式 json

javascript - 选中复选框时如何刷新页面的一部分?

javascript - VUE.JS 将数据传递给 D3 - 做对了吗?

Javascript - 解析 - 云代码 - beforeSave 和 afterSave

javascript - 如何获取字符串中从头到尾的字母索引?

c# - 修剪字符串中的字符