繁体   English   中英

搜索完整的单词而不是其中的一部分

[英]Search for full word instead of part inside of it

我试图在用户发送的文本中找到确切的单词,但显然,当我尝试使用message.content.includes()时,它也在寻找我不需要的文本中的部分单词? 有什么办法只按全词搜索吗?

几个例子: **TexT**HeLlO等。

是的,您可以使用这样的正则表达式,假设wordToFind包含您正在搜索的单词:

// Create regex from word with \b at each end which
// means "word boundary", and the 'i' option means
// case-insensitive
const wordSearch = new RegExp(`\b${wordToFind}\b`, 'i');

// Use the regular expression to test the content:
const hasWord = wordSearch.test(message.content);

// will be true if whole word is found

将您的内容放入一个数组中,如果它是一段文本,则拆分单词。 Array.includes将匹配整个单词。

所以要么[content].includes(word)要么content.split(' ').includes(word)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM