I want a Javascript code which extract values from an input by a template
for example
template
Ahmed love eating {food} with {person}
input
Ahmed love eating Burger with Mohsen
I want the code to output the values as object
{
food: "Burger",
person: "Mohsen"
}
the code should be flexible to handle any template, read the variables and extract it from the input
I asked ChatGPT, it did his best to generate a functional code but was not flexible to handle more templates
the code which ChatGPT generated
const parser = (template, input) => {
// Use a regular expression to extract the values from the input string
const regex = /{(\w+)}/g;
let match;
const values = {};
while ((match = regex.exec(template))) {
const key = match[1];
const startIndex = match.index;
const endIndex = regex.lastIndex;
const value = input
.substring(startIndex - 1, endIndex)
.replace(/[{}]/g, '')
.trim();
values[key] = value;
}
return values;
};
It's okay to use a libraries or frameworks to achieve that goal, in case the algorithm will be very big