JavaScript使用matchAll时如何仅替换4个正则匹配项中的前3个
问题解决:正则匹配后仅替换前3个匹配项
报错原因
- 你代码中的
replacements是普通数组类型,没有next()方法,next()是迭代器对象的专属API,直接调用会抛出类型错误
实现方案
方案1:基于迭代器实现
把替换值数组转为迭代器后再按逻辑调用next()即可,多余的匹配项直接返回原字符不替换:
let test = ". . . ."; const regex = /\./gm; // 验证匹配总数为4 let matchAll = test.matchAll(regex); console.log(Array.from(matchAll).length); const replacements = [1, 2, 3]; // 将数组转为迭代器 const replaceIterator = replacements[Symbol.iterator](); test = test.replace(regex, (matchItem) => { const iteratorRes = replaceIterator.next(); // 迭代器未耗尽时用替换值,耗尽则返回原匹配项不替换 return iteratorRes.done ? matchItem : iteratorRes.value; }); console.log(test); // 输出结果:1 2 3 .
方案2:基于计数器实现(更直观)
用计数器控制替换次数,逻辑更简单易懂:
let test = ". . . ."; const regex = /\./gm; const replacements = [1, 2, 3]; let replaceCount = 0; test = test.replace(regex, (matchItem) => { return replaceCount < replacements.length ? replacements[replaceCount++] : matchItem; }); console.log(test); // 输出结果:1 2 3 .
内容的提问来源于stack exchange,提问作者user310291
相关产品推荐
相关产品推荐

