Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
matchAll: cómo reemplazar solo los primeros 3 partidos sobre 4

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);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!