Tam2
Tam2

Reputation: 345

Replace all variables in string using RegEx

Using a combination of a couple of previous answers I've tried to put together a RegEx that'll allow me to replace all occurrences of anything within curly braces

I got this far, but it doesn't seem to work

var str = "The {type} went to the {place}";


var mapObj = {
   type: 'Man',
   place: "Shop"

};
var re = new RegExp(/(?<=\{)Object.keys(mapObj).join("|")(?=\})/, "gim");
str = str.replace(re, function(matched){
  return mapObj[matched.toLowerCase()];
});

console.log(str);

I added (?<={) and (?=}) to the previous answer to have it only match occurrences where the key was within curly braces

Previous Answer - Replace multiple strings with multiple other strings

Upvotes: 0

Views: 161

Answers (1)

Ori Drori
Ori Drori

Reputation: 191946

Use a capture group, and you'll get the value as the 2nd param of the replace callback:

var str = "The {type} went to the {place}";

var mapObj = {
  type: 'Man',
  place: "Shop"

};

str = str.replace(/\{([^{}]+)\}/gim, function(_, c) {
  return mapObj[c.toLowerCase()] || `{${c}}`;
});

console.log(str);

Upvotes: 3

Related Questions