Skip to content

Dynamically replace data based on matched RegEx JavaScript

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.



Luckily, replace() allows to use a callback:

matchesMessage = template.replace(
    (match, tag) => data[tag.trim()]

// "There are six matches for the category shoes."
User contributions licensed under: CC BY-SA
7 People found this is helpful