I would like to create an HTML input form that converts every typed numerical value into a subscript. The numerical value that is typed into the input form, should immediately appear as a subscript while typing.
I am making a molar mass calculator for chemical formulas and it would be nice to show the correct form of a chemical formula. Users could, for example, type O2 into the input form and it should appear as O₂.
I have tried the following:
JavaScript:
const inputFormula = document.getElementById("input-formula");
inputFormula.addEventListener("input", function () {
inputFormula.value = inputFormula.value.replace(/(\d+)/g, "<sub>$1</sub>");
});
On change of the input field, the JavaScript code will convert every number into a subscript, at least that was the idea, but it doesn't work.
HTML:
<input type="text" id="input-formula" placeholder="formula" required>
However, when typing a number into the input field, the numbers are replaced with <*sub>"number"</*sub>, while I would like it to be replaced with the number displayed as subscript. Is this possible in HTML?
I added the * to prevent the sub tag from functioning as code
Any suggestions are welcome!! Thanks in advance!