Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
matchAll: how to replace only first 3 matchs over 4

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);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Something like this:

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

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda