I have a string that contains template interpolation along with words that are not inside the interpolation. The string can be in one of these various forms:
foo{{bar}}
{{foo}}bar
foo{{bar}}baz
{{foo}}{{bar}}
foo
{{foo}}
{{foo}}bar{{baz}}
The text interpolation can appear multiple times in the string and there can be more than one word not inside the interpolation.
I need to transform the string as follows: remove the double curly brackets and keep the content, while the words outside the brackets should be wrapped in single quotes and concatenated using +
.
The final result should generate a new string like this:
foo{{bar}} // <-- 'foo' + bar
{{foo}}bar // <-- foo + 'bar'
foo{{bar}}baz // <-- 'foo' + bar + 'baz'
{{foo}}{{bar}} // <-- foo + bar
foo // <-- 'foo'
{{foo}} // <-- foo
{{foo}}bar{{baz}} //<-- foo + 'bar' + 'baz'
For this, I created a regex expression
str.replace(/{{(.*?)}}/g, '$1').replace(/\b(\w+)\b/g, "'$1'")
The first regex removes the double curly brackets. The second regex wraps words in single quotes.
However, every result is getting wrapped in single quotes and there is no concatenation between them (not sure where to use +
in which regex).
How can I modify the regex to meet my requirements?
const strs = [
'foo{{bar}}',
'{{foo}}bar',
'foo{{bar}}baz',
'{{foo}}{{bar}}',
'foo',
'{{foo}}',
'{{foo}}bar{{baz}}'
];
let result = strs.map((s) =>
s.replace(/{{(.*?)}}/g, '$1').replace(/\b(\w+)\b/g, "'$1'")
);
result.forEach((r) => console.log(r));