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

1
  • I would try simply /\{([^}]+)\}/ to match on any string surrounded by curly braces. Commented Jan 3, 2020 at 18:01

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Something like return mapObj[c.toLowerCase()] !== undefined ? mapObj[c.toLowerCase()] : '{'+c+'}'; would fix it.
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
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.