0

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

Tam2
  • 323
  • 1
  • 5
  • 16

1 Answers1

3

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Given the nature of OP's question I would imagine there will be instances where a variable in the string does not have a match in the `mapObj`. – MonkeyZeus Jan 03 '20 at 18:05
  • Something like `return mapObj[c.toLowerCase()] !== undefined ? mapObj[c.toLowerCase()] : '{'+c+'}';` would fix it. – MonkeyZeus Jan 03 '20 at 18:07
  • That works perfectly, added the suggestion from @MonkeyZeus as there could be instances where a variable doesn't match a key within mapObj so better to return it as it was – Tam2 Jan 03 '20 at 18:11
  • @TamoorMalik I would suggest using the `return` statement from my comment because it would properly handle mismatched data types so that you could do something like `type: 0` reliably. – MonkeyZeus Jan 03 '20 at 18:15