Maxim
Maxim

Reputation: 51

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.

Upvotes: 0

Views: 811

Answers (2)

Jesse Nguyen
Jesse Nguyen

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

Robo Robok
Robo Robok

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

Related Questions