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

如何对比字符串与数组,仅匹配独立存在的词或短语?

独立词/短语匹配解决方案

你的问题在于includes()方法会匹配任意子字符串,而非独立的词或短语。要解决这个问题,我们可以用正则表达式精准匹配被空白或字符串边界包裹的完整内容,避免子片段误匹配。

修改后的代码

const userInput = "hello good morning everyone";
const myArray = ["tomorrow", "morning", "good", "good morning", "go", "he"];

// 转义正则特殊字符,避免匹配出错
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

const intersect = myArray.filter(word => {
  // 构造正则:匹配开头/空格 + 目标内容 + 空格/结尾
  const matchPattern = new RegExp(`(?:^|\\s)${escapeRegExp(word)}(?:\\s|$)`);
  return matchPattern.test(userInput);
});

document.write(intersect); // 输出:morning,good,good morning

代码说明

  • escapeRegExp函数:转义字符串中的正则特殊字符(如.、*、+等),确保数组中包含特殊字符时正则能正常工作。
  • 正则匹配逻辑:
    • (?:^|\\s):匹配字符串开头或任意空白字符(非捕获组,不存储匹配结果)
    • ${escapeRegExp(word)}:转义后的目标词/短语
    • (?:\\s|$):匹配任意空白字符或字符串结尾
  • test()方法:替代includes(),仅当存在完整匹配时返回true。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:10:30