Home > OS >  matchAll: how to replace only first 3 matchs over 4
matchAll: how to replace only first 3 matchs over 4

Time:10-22

This code generates errors and I want to replace only first 3 over 4 match

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);

CodePudding user response:

Something like this:

let test = ". . . .";
const regex = /\./m;
const replacements = [1, 2, 3];
replacements.forEach((replacement) => test = test.replace(regex, replacement));
console.log(test);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I remove the global flag from the regular expression to only replace the first match found, and then loop through the replacements array.

CodePudding user response:

1) You can initialize the couter to 0 and then replace it with replacement array data until 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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

2) If you want to generalise it then you can add one more condition 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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related