I am looking for specific regex matches in a text in a contenteditable
div. I do find the correct matches:
<script>
const regex = /my_regex/g;
let content = $("#contenteditable").text();
let matches = content.match(regex);
if (matches) {
matches.forEach((match, groupIndex) => {
// it finds the correct matches.
});
}
</script>
I want to highlight the matches in the text by wrapping each match in a <span>
element with some styling
At first I tried using content.replace(//..)
and then document.getElementById('contenteditable').textContent = content;
or other methods using innerHTML
but realized that it just reloads everything and not allowing the user to keep typing in the contenteditable
div.
So I think the only way to do it is actually get the position of each match and replace each occurrence alone
So I found this post: Get a range's start and end offset's relative to its parent container
But then even if I have the caret position for each match, how can I replace only that? Is there any less complicated way to replace matches "on the fly" (as the user keeps typing without interrupting him), or it has to be done in these complicated ways?