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

如何使用JavaScript对比两个字符串并返回不匹配内容

字符串差异提取实现方案

功能说明

针对两个字符串的对比需求,提取二者不匹配的内容,适配你给出的前缀相同的场景,也可兼容任意位置出现差异的场景。

代码实现

function getUnmatchedContent(strA, strB) {
  // 逐位对比找到首个差异位置
  let samePrefixEndIndex = 0;
  const minLen = Math.min(strA.length, strB.length);
  while (samePrefixEndIndex < minLen && strA[samePrefixEndIndex] === strB[samePrefixEndIndex]) {
    samePrefixEndIndex++;
  }
  // 按你的示例需求,返回str2中不匹配的部分(去除多余空格)
  return strB.slice(samePrefixEndIndex).trim();
  // 若需要返回两边所有不匹配内容,可替换为如下代码:
  // return {
  //   strAUnmatched: strA.slice(samePrefixEndIndex),
  //   strBUnmatched: strB.slice(samePrefixEndIndex)
  // }
}

// 测试你的示例
const string1 = "string";
const string2 = "string 2";
console.log(getUnmatchedContent(string1, string2)); // 输出:2

扩展说明

  • 如果你的匹配场景不是前缀匹配,而是需要提取两个字符串的所有不同字符,可调整对比逻辑为全字符遍历匹配即可。
  • 若需要忽略大小写、忽略空白字符对比,可在逐位判断前先将字符统一转换为大小写、去除空白后再做相等判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:39:04