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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This looks great, but I updated my answer, I am looking for a version that can use dynamic variables. Here Tushar and secret are hard coded.
@Startec You can assign the values when creating object. As you've variables, you can use those as values in object.
don't I have to pass in replacements to Object.keys()?
@Startec sorry, my mistake. Thanks for correcting me. :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.