首页 > 解决方案 > matchAll:如何仅替换前 3 个匹配项超过 4 个

问题描述

此代码生成错误,我只想替换前 3 比 4 匹配

https://jsfiddle.net/9Lfj0dva/

let test = ". . . .";
const regex = /\./gm;
let matchAll = test.matchAll(regex);
console.log(Array.from(matchAll).length);
const replacements = [1, 2, 3];
test = test.replace(regex, () => replacements.next().value);
console.log(test);

标签: javascriptregex

解决方案


像这样的东西:

let test = ". . . .";
const regex = /\./m;
const replacements = [1, 2, 3];
replacements.forEach((replacement) => test = test.replace(regex, replacement));
console.log(test);

我从正则表达式中删除全局标志以仅替换找到的第一个匹配项,然后循环遍历替换数组。


推荐阅读