【问题标题】:Search for full word instead of part inside of it搜索完整的单词而不是其中的一部分
【发布时间】:2022-01-24 03:48:19
【问题描述】:

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

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

【问题讨论】:

  • 您可以使用regex 正则表达式仅搜索完全匹配。
  • 您应该添加一些用户输入的文本和单词的示例,以使您的问题更清晰。
  • @ZsoltMeszaros 基本上应该是类似坏词过滤器的东西
  • 为什么不干脆做String#includes(" text ")(开头和结尾的空格)之类的东西

标签: javascript node.js discord discord.js bots


【解决方案1】:

是的,您可以使用这样的正则表达式,假设 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

【讨论】:

    【解决方案2】:

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

    因此,如果内容是单个词,则使用 [content].includes(word),如果内容是多个词,则使用 content.split(' ').includes(word)

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      相关资源
      最近更新 更多