matchAll:如何只替换4个以上的前3个匹配



这段代码会产生错误,我想只替换前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);

像这样:

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

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

1)您可以将计数器初始化为0,然后将其替换为替换数组数据,直到index < length - 1

let test = ". . . .";
const regex = /./gm;
let matchAll = [...test.matchAll(regex)];
const replacements = [1, 2, 3];
let index = 0;
const length = matchAll.length;
const result = test.replace(regex, (match) => index < length - 1 ? replacements[index++] : match );
console.log(result);

2)如果你想推广它,你可以再加一个条件index < replacements.length

let test = ". . . . . .";
const regex = /./gm;
let matchAll = [...test.matchAll(regex)];
const length = matchAll.length;
const replacements = [1, 2, 3];
let index = 0;
const result = test.replace(regex, (match) =>
index < length - 1 && index < replacements.length
? replacements[index++]
: match
);
console.log(result);

相关内容

最新更新