JSFiddle - React, Tailwind, and code Playground

by OjisanSeiuchi

HTML

<div id="front-sentence">
|C'/Il |est essentiel* + {{c1::de + infinitif}} ou {{c2::que + subjonctif}}

*obligatoire
*nécessaire
*important
*indispensable
</div>

JavaScript

function unslash(text) {
  let options = text.match(/\|([^\|]+)\|/);
  //console.log(options);
  let choices = options[1].split('/');
  let chosen = choices[choices.length * Math.random() | 0];
  text = text.replace(options[0], chosen);
  return text;
}

function unstar(text) {
  let options = text.match(/\s+([^\s\*]+\*)\s+/);
  let targetStar = options[1];
  let targetUnstar = targetStar.replace('*', '');
  // now find the options for replacement
  let starOptionsIter = text.matchAll(/^(\*[^\*\s]+)$/gm);
  // only keep the 1st match group of each
  let starOptions = Array.from(starOptionsIter).map(x => x[0]);
  let starOptionsUnstar = starOptions.map(x => x.replace('*', ''));
  // add our targetUnstar = 
  starOptionsUnstar.push(targetUnstar);
  //console.log(starOptionsUnstar);
  let starChosen = starOptionsUnstar[starOptionsUnstar.length * Math.random() | 0];
  // now replace the targetStar with the chosen
  //console.log(starChosen);
  text = text.replace(targetStar, starChosen);
  // clean up the option list so we don't reveal our sources
  starOptionsIter = text.matchAll(/^(\*[^\*\s]+)$/gm);
  for (let opt of starOptionsIter) {
    text = text.replace(opt[0], '').trim();
  }
  return text;
}

function remarkCloze() {
  let clozeEl = document.querySelector('#front-sentence');
  let sentenceText = clozeEl.textContent;
  sentenceText = unslash(sentenceText);
  //console.log(sentenceText);
  sentenceText = unstar(sentenceText);
  console.log(sentenceText);
}

if (document.readyState !== 'loading') {
  remarkCloze();
} else {
  document.addEventListener('DOMContentLoaded', remarkCloze);
}