I have the following sentence with quiz items to solve.
With regex I can easily identify these items and replace them with a text, e.g. to get a quiz sentence.
However, can replace the items with an array of strings, e.g. so that I can build the correct sentence by replacing each item with its appropriate answer?
const regex = /(\[.*?\])/gm;
const text = 'This [is/are] a sentence, and those [is/are] some apples.';
const answers = ['is', 'are'];
const replaceAllRegex = (text, regex, replace) => text.replace(new RegExp(regex, 'g'), replace);
const phrases = {};
phrases.cloze = replaceAllRegex(text, regex, '[_________]');
for (const answer of answers) {
phrases.right = replaceAllRegex(text, regex, answer);
}
console.log(phrases.cloze);
// OUTPUTS: This [_________] a sentence, and those [_________] some apples.
console.log(phrases.right)
// OUTPUTS: This are a sentence, and those are some apples.
// SHOULD OUTPUT: This is a sentence, and those are some apples.
phrases.rightevery time through the loop. The first time will useis, the second time will useare.g(global). Then you can iterate and replace individually.