I am trying to refactor some code:
const newValue = value
.replace(/\{1\}/g, '<i class="ms ms-1 inline"></i>')
.replace(/\{2\}/g, '<i class="ms ms-2 inline"></i>')
... etc etc
return newValue;
I would prefer not to use replace
each time.
I have been trying the following without success:
const mapObj = {
'/\{1\}/': '<i class="ms ms-1 inline"></i>',
'/\{2\}/': '<i class="ms ms-2 inline"></i>',
...
}
const reg = new RegExp(Object.keys(mapObj).join("|"), "g");
return value.replace(reg, (m) => mapObj[m]);
For simple replaces this usually works pretty well, however because of the need to escape the special characters ({
and }
) something is clearly going wrong with my regex pattern in the mapObj
object.
Here is demo of the current simplified code.
How do I go about fixing the pattern (/\{1\}/
) in the mapObj
to get the refactored code to work?