I have been trying to add text highlighting to python code in a writable div using spans since spans do not work inside textarea, but for some reason the div reverses any text, here's a simplified version of the code:
<div id="code-editor" spellcheck="false" contenteditable="true"></div>
<script>
const writableDiv = document.getElementById("code-editor");
const pythonKeyWords = [ /* has all python keywords */ ]
const keywordRegex = new RegExp('\\b(' + pythonKeywords.join('|') + ')\\b', 'g');
writableDiv.addEventListener('input', () => {
let text = writableDiv.innerText;
text = text.replace(keywordRegex, '<span style="color: #f200ff;">$&</span>');
writableDiv.innerHTML = text;
});
</script>
Here, if I enter def
from the keyword, it comes out as fed
in the the div, and vice versa.
I would like to know what's wrong with what I am doing, because I have tried to use highlights.js
and to customize it a bit but it got the same issue as this one.