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

如何按首次匹配的子字符串将目标字符串拆分为3个部分

字符串按首次匹配子串拆分实现方案

split方法本身的设计无法满足需求:split拆分后的返回结果不会包含分隔符本身,即使设置拆分次数,也只会返回前N个拆分后的片段,既不会保留匹配的子串,也不会自动将剩余内容合并为第三部分。

实现逻辑

通过indexOf获取子串首次匹配的起始索引,再按位置手动切割即可,步骤如下:

  1. 调用indexOf查找目标子串第一次出现的索引,若不存在匹配,可根据需求返回[原字符串, '', '']
  2. 前缀部分:原字符串从起始位置截取到子串的起始索引
  3. 匹配部分:直接使用传入的子串本身
  4. 后缀部分:原字符串从「子串起始索引 + 子串长度」的位置截取到末尾

可直接运行的代码

function splitByFirstMatch(originStr, keyword) {
  const matchIndex = originStr.indexOf(keyword);
  // 无匹配的情况
  if (matchIndex === -1) {
    return [originStr, '', ''];
  }
  return [
    originStr.slice(0, matchIndex),
    keyword,
    originStr.slice(matchIndex + keyword.length)
  ];
}

// 测试验证
const testStr = 'test01String001s';
// 用例1 子串为"0"
console.log(splitByFirstMatch(testStr, '0')); // 输出:["test","0","1String001s"]
// 用例2 子串为"st"
console.log(splitByFirstMatch(testStr, 'st')); // 输出:["te","st","01String001s"]
// 用例3 子串为"01s"
console.log(splitByFirstMatch(testStr, '01s')); // 输出:["test01String0","01s",""]
// 用例4 子串为"t"
console.log(splitByFirstMatch(testStr, 't')); // 输出:["","t","est01String001s"]

该方案不需要处理正则特殊字符转义问题,性能更稳定,适合所有场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:27:02