如何按首次匹配的子字符串将目标字符串拆分为3个部分
字符串按首次匹配子串拆分实现方案
split方法本身的设计无法满足需求:split拆分后的返回结果不会包含分隔符本身,即使设置拆分次数,也只会返回前N个拆分后的片段,既不会保留匹配的子串,也不会自动将剩余内容合并为第三部分。
实现逻辑
通过indexOf获取子串首次匹配的起始索引,再按位置手动切割即可,步骤如下:
- 调用
indexOf查找目标子串第一次出现的索引,若不存在匹配,可根据需求返回[原字符串, '', ''] - 前缀部分:原字符串从起始位置截取到子串的起始索引
- 匹配部分:直接使用传入的子串本身
- 后缀部分:原字符串从「子串起始索引 + 子串长度」的位置截取到末尾
可直接运行的代码
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
相关产品推荐
相关产品推荐

