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

151
Views
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 answers
Answer question

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 Report

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 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!