此代碼生成錯誤,我只想替換前 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);
uj5u.com熱心網友回復:
像這樣的東西:
let test = ". . . .";
const regex = /\./m;
const replacements = [1, 2, 3];
replacements.forEach((replacement) => test = test.replace(regex, replacement));
console.log(test);
我從正則運算式中洗掉全域標志以僅替換找到的第一個匹配項,然后遍歷替換陣列。
uj5u.com熱心網友回復:
1)
您可以將couter初始化為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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334551.html
標籤:javascript 正则表达式
