Reputation: 51
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.
Upvotes: 0
Views: 811
Reputation: 66
So just to be clear, you have an object with various properties, and you simply want to embed the values of those properties inside of a string?
One possible solution is to use template literals, which allow you to embed data inside of a string. Basically, enclose your string inside of backticks instead of single or double quotes, and then surround expressions that represent your data with ${}
Upvotes: 1
Reputation: 22765
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."
Upvotes: 5