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

JavaScript实现两字符串重叠片段查找(支持首尾及中间匹配)

JavaScript 全场景字符串重叠检测实现

需求场景

需要检测搜索字符串与目标字符串的重叠片段,覆盖三类匹配规则:

  • 搜索串前缀与目标串结尾重叠:目标串为click on the Run、搜索串为the Run button to时,返回重叠片段the Run
  • 搜索串后缀与目标串开头重叠:目标串同上、搜索串为code and click on时,返回重叠片段click on
  • 搜索串完全匹配目标串中间片段:目标串同上、搜索串为on the时,返回匹配结果on the

原有代码缺陷

现有拆分的两个递归检测函数存在以下问题:

  • 无法自动判断重叠类型,必须提前知晓重叠位置才能调用对应函数
  • 逻辑分散,未覆盖中间片段匹配场景
  • 递归终止条件硬编码为长度2,灵活性差,长字符串场景存在栈溢出风险

整合实现代码

function findOverlap(target, search, minMatchLen = 2) {
  const targetLen = target.length;
  const searchLen = search.length;
  if (searchLen < minMatchLen) return "";

  // 优先匹配完整子串(覆盖中间片段、全包含场景)
  if (target.includes(search)) return search;

  // 检测搜索串前缀与目标串结尾的重叠,从最长可能长度向下遍历
  const maxOverlapLen = Math.min(targetLen, searchLen);
  for (let len = maxOverlapLen; len >= minMatchLen; len--) {
    const prefix = search.slice(0, len);
    if (target.endsWith(prefix)) return prefix;
  }

  // 检测搜索串后缀与目标串开头的重叠,从最长可能长度向下遍历
  for (let len = maxOverlapLen; len >= minMatchLen; len--) {
    const suffix = search.slice(-len);
    if (target.startsWith(suffix)) return suffix;
  }

  return "";
}

// 测试用例
console.log(findOverlap("click on the Run", "the Run button to")); // 输出 "the Run"
console.log(findOverlap("click on the Run", "code and click on")); // 输出 "click on"
console.log(findOverlap("click on the Run", "on the")); // 输出 "on the"
console.log(findOverlap("click on the Run", "unmatched str")); // 输出 ""

逻辑说明

  • 匹配优先级:完整子串匹配 > 结尾重叠 > 开头重叠,所有场景均优先返回最长匹配片段
  • 用循环替代原有递归实现,避免长字符串递归栈溢出问题
  • 最小匹配长度支持自定义配置,不再硬编码固定值
  • 单次调用即可覆盖全部三类场景,无需提前预判重叠位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 00:24:44