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

78
Views
ReplaceAll not replacing all in recursive function

I'm using a recursive function that takes a template string like this:

<div class='${classes}'>

and replaces the template literal placeholder ${classes} with valued from an object that looks like this:

{ classes: 'bg-${color} text-${color}', color: 'blue' }

Something to note here is that within the object, there is more template string nesting, hence the reason for the recursive function.

The thing I cannot work out is why the replace all function is only replacing the 1st instance of ${color}, and leaving the second undefined.

Working snippet below:

function buildTemplate(string) {
  var matched = false;
  string = string.replaceAll(/\$\{(.*?)\}/g, function (match, key) {
    if (match) {
      matched = true;
    }
    const selection = selectors[key];
    delete selectors[key];
    return selection;
  });
  if (matched) {
    string = buildTemplate(string);
  }
  console.log(string);
}

let templateString = "<div class='${classes}'>";
const selectors = { classes: 'bg-${color} text-${color}', color: 'blue' }
buildTemplate(templateString);

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You are deleting selectors, when you need it twice.
Remove line;

// delete selectors[key]

or selection get assigned nothing

No need to delete anything when it's an object that is accessed through a key.

about 4 years ago · Santiago Gelvez 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!