Ad

Only Last Item Of Array Is Replaced

I need to replace variables for the body of an email. If the name of the variables exists in the variableNames array, then it must be replaced.

But the problem is that only the last one that corresponds to the last name of the variableNames Names is replaced (in my case: 'NAME4'). What am I doing wrong? How can I solve it?

var variableNames = [
  'NAME1',
  'NAME2',
  'NAME3',
  'NAME4'];

var regex = '';
var key2 = '';
var position = '';

for (var key in variables) {

  if (variableNames.includes(key)) {

    position = variableNames.indexOf(key);
    key2 = variableNames[position];
    regex = new RegExp("###" + key2 + "###", "g");

    template.content = template.body.replace(regex, variables[key2]); 
    //only replace the last one
  }

}
Ad

Answer

The input string you're replacing is always template.body (so, after each iteration, only the original string, replaced once, is assigned to template.content).

Save the string you're replacing in a variable.

Also, because you're looking for the key in the variableNames array, and constructing the regex from that, an includes check is enough - just pass the key to new RegExp, no need to search the array again to acquire the variable you already have:

const variableNames = [
  'NAME1',
  'NAME2',
  'NAME3',
  'NAME4'
];

let tempString = template.body;
for (const key in variables) {
  if (variableNames.includes(key)) {
    const regex = new RegExp("###" + key + "###", "g");
    tempString = tempString.replace(regex, variables[key]);
  }
}
template.content = tempString;

This could probably be done even more elegantly with a replacer function, but it's hard to say what exactly the code would be like without knowing a bit more about variables.

Ad
source: stackoverflow.com
Ad