批量搜索或单词搜索(不是字母)

Search in bulk or word (not letters)

我想在变量内部搜索,但我不希望它搜索字母作为

示例:

const myText = "Hi Here We go";
console.log(myText.includes("Here")) // true
console.log(myText.includes("ere")) // false
console.log(myText.includes("Here We")) // true
console.log(myText.includes("go")) // true
console.log(myText.includes("i")) // false

一个方案是把要搜索的字符串变成正则表达式,左右加上分界线。

const myText = "Hi Here We go";
console.log(/\bHere\b/.test(myText));
console.log(/\bere\b/.test(myText));

如果你必须动态地做...

const myText = "Hi Here We go";
const validate = needle => (new RegExp('\b' + needle + '\b')).test(myText);
console.log(validate('Here'));
console.log(validate('ere'));