Startec
Startec

Reputation: 13216

How to replace several different items in a template text document in JavaScript

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.

Upvotes: 1

Views: 78

Answers (2)

Tushar
Tushar

Reputation: 87233

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.

Upvotes: 2

Alexander O'Mara
Alexander O'Mara

Reputation: 60577

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.

Upvotes: 1

Related Questions