You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS小型聊天机器人开发:检测字符串含指定列表词汇的优化方案

优化JS聊天机器人的关键词匹配逻辑

我明白你的困扰——手动写一堆if-else去检测每个词汇确实容易越写越乱,尤其是以后要扩展更多触发词组的时候!这里有几个清晰、可维护的优化方案,帮你把逻辑理顺:

方案一:封装通用检测函数,简化判断逻辑

先把「检测输入是否包含指定词汇组中内容」的逻辑抽成一个通用函数,这样不管有多少词汇组,都能用同一个函数去判断,避免重复代码:

// 定义你的词汇组
const helloWords = ["hello", "salut", "hi", "yo", "hey"];
const howWords = ["how are you", "what's up", "how is it going", "how do you do"];

// 通用检测函数:忽略大小写,判断输入是否包含目标词汇/短语
function hasMatch(input, keywordList) {
  const lowerInput = input.toLowerCase();
  return keywordList.some(keyword => lowerInput.includes(keyword.toLowerCase()));
}

// 机器人回复逻辑
function getBotReply(userInput) {
  if (hasMatch(userInput, helloWords)) {
    return "Hey there! 😊";
  } else if (hasMatch(userInput, howWords)) {
    return "I'm doing great, thanks for asking! How about you? 🤗";
  } else {
    return "Sorry, I didn't get that. Could you rephrase? 😅";
  }
}

// 测试一下
console.log(getBotReply("Hi, how's it going?")); // 会触发hello的回复,因为先匹配到hi
console.log(getBotReply("What's up dude?")); // 触发how类回复

方案二:用映射表管理规则,更易扩展

如果以后要加更多触发词和对应的回复,用「触发词组-回复」的映射表会更方便——新增规则只需要在映射表里加条目,不用修改判断逻辑:

// 定义触发规则:键是回复内容,值是对应的词汇组
const replyRules = {
  "Hey there! 😊": ["hello", "salut", "hi", "yo", "hey"],
  "I'm doing great, thanks for asking! How about you? 🤗": ["how are you", "what's up", "how is it going", "how do you do"],
  // 以后加新规则直接在这里加就行
  "That's awesome to hear! 😄": ["good", "great", "awesome", "fantastic"]
};

// 通用检测函数(和方案一一样)
function hasMatch(input, keywordList) {
  const lowerInput = input.toLowerCase();
  return keywordList.some(keyword => lowerInput.includes(keyword.toLowerCase()));
}

// 机器人回复逻辑
function getBotReply(userInput) {
  // 遍历所有规则,返回第一个匹配到的回复
  for (const [reply, keywords] of Object.entries(replyRules)) {
    if (hasMatch(userInput, keywords)) {
      return reply;
    }
  }
  // 没有匹配到的默认回复
  return "Sorry, I didn't get that. Could you rephrase? 😅";
}

// 测试
console.log(getBotReply("Salut! Comment ça va?")); // 触发hello回复
console.log(getBotReply("I'm feeling fantastic today!")); // 触发新增的回复

额外优化:精确匹配单词边界(可选)

如果担心部分匹配的问题(比如输入"how are your cat"被误判成匹配"how are you"),可以用正则表达式匹配单词边界,这样只会匹配完整的词汇/短语:

function hasMatch(input, keywordList) {
  return keywordList.some(keyword => {
    // 转义正则特殊字符(比如短语里的'、?等)
    const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    // 用正则匹配单词边界,忽略大小写
    const regex = new RegExp(`\\b${escapedKeyword}\\b`, 'i');
    return regex.test(input);
  });
}

这些方案的核心都是把重复逻辑抽离、用结构化的方式管理规则,这样你的代码会越来越清晰,不会随着词汇组增加而混乱~

内容的提问来源于stack exchange,提问作者Enhancer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:10:46