Search code examples
javascriptreplacereplaceall

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


Solution

  • 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.