I have a dynamic template string, similar to the following:
There are {{num}} matches for the category {{category}}.
I also have an object like so:
let data = { "num": // some value "category": // another value }
How do I replace each template variable with the value presented in an object where the key is the text in the braces. For example:
// example object let data = { "num": "six", "category": "shoes" } // result "There are six matches for the category shoes"
I have tried the following:
messageRegEx = /{{(.*)}}/g matchesMessage = template.replace(messageRegEx, data["$1"])
The code above replaces all instances of text in curly braces with undefined
. I have looked at multiple StackOverflow questions, but none have addressed this issue.
Advertisement
Answer
Luckily, replace()
allows to use a callback:
matchesMessage = template.replace( /{{(.+?)}}/g, (match, tag) => data[tag.trim()] ); console.log(matchesMessage); // "There are six matches for the category shoes."