Este código genera errores y quiero reemplazar solo las primeras 3 sobre 4 coincidencias
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);Algo como esto:
let test = ". . . ."; const regex = /\./m; const replacements = [1, 2, 3]; replacements.forEach((replacement) => test = test.replace(regex, replacement)); console.log(test);Elimino la marca global de la expresión regular para reemplazar solo la primera coincidencia encontrada y luego recorro la matriz de reemplazos.
1) Puede inicializar el contador a 0 y luego reemplazarlo con datos de matriz de reemplazo hasta que el 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) Si desea generalizarlo, puede agregar un 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);