Is there a fast regex method or similar that can take a string and parse it into bits not in double-curly brackets (let's call those "static") and bits that are in double-curly brackets (let's call those "dynamic")?
For example, input:
Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}.
Required output:
[
{
type: "static",
value: "Lorem "
},
{
type: "dynamic",
value: "ipsum dolor sit"
},
{
type: "static",
value: " amet, {consectetur} adipiscing "
},
{
type: "dynamic",
value: "elit"
},
{
type: "static",
value: "."
},
]
My best try so far has been to use /\{*([^{}]+)\}*/g as a regex and loop through using while and exec but it incorrectly identifies any number of curly brackets as dynamic values, as shown here:
function templateParser(string) {
const re = /\{*([^{}]+)\}*/g;
const output = [];
while (true) {
const match = re.exec(string);
if (!match) {
break;
}
const [templateItem, templateKey] = match;
output.push({
type: templateItem === templateKey ? "static" : "dynamic",
value: templateItem === templateKey ? templateItem : templateKey
});
}
return output;
}
console.log(
templateParser(
"Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}."
)
);