1

I am trying to create a service where an email is sent after an http request is made. I have several variables defined within the text of the document, something like #FIRSTNAME #LASTNAME etc. and after an even I want to replace these with information received by the post (i.e. dynamically and not prior known variables).

The current method I am using involved a regex method of

matcha = /#FIRSTNAME/
matchb = /#LASTNAME/

But after only those two emails I have a pretty long code string that looks like:

 let outgoingEmail = data.replace(matcha, vara).replace(matchb, varb)

Is there a more concise way to replace several matches or do I have to just chain all of the matches together?

With two I guess this is tolerable but I would like to replace many and I am wondering how things like email templating services typically handle this.

Startec
  • 12,496
  • 23
  • 93
  • 160
  • 1
    This looks very similar to [another question that I posted](http://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings) several years ago. – Anderson Green Dec 21 '16 at 03:48

2 Answers2

2

Create an object to store the needles and their replacement. Using Object.keys() to get all the keys in the object and RegExp constructor, create a regex with OR | in the keys.

Then use String#replace with function to replace the needles by their values from the object.

var replacements = {
    '#FIRSTNAME': 'Tushar',
    '#LASTNAME': 'Secret'
    ...
};

var regex = new RegExp(Object.keys(replacements).join('|'), 'g');
// Use `i` flag to match case-insensitively

data.replace(regex, function(m) {
    return replacements[m] || m;
});

Note: If the string to find contains characters having special meaning in regex, they need to be escaped before creating regex from string.

Tushar
  • 85,780
  • 21
  • 159
  • 179
1

You can make a basic template engine rather easily if you use .replace with a callback function, and supply an object with variable names.

Simple Example:

var data = '\n' +
 'firstname:  #FIRSTNAME\n' +
 'lastname: #LASTNAME\n' +
 '\n';

var replace = {
 FIRSTNAME: 'John',
 LASTNAME: 'Smith'
};

var message = data.replace(/#([A-Z]+)/g, function(all, word) {
 return replace[word];
});

console.log(message);

The regex I used will match any #'s followed by all-capital-letters. You can adjust it to your needs.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171