I am trying to build a WYSIWYG markdown editor using a <div>
with the contentEditable
attribute.
Each time a keyup
event fires, I am using str.replace
with a regular expression to find instances of markdown syntax. For example, in the string "this text is **bold**
", I use HTML to make the text appear bold in real-time.
However, on each key press and update of the "pseudo-field", the caret/cursor returns to the start. I have tried various strategies to reposition it, including selectionStart
and selectionEnd
, but it seems these attributes are not applicable to a <div>
(they are undefined).
var editor = document.getElementById('editor');
editor.addEventListener('keyup', function (e) {
var doc = editor.innerHTML;
editor.innerHTML = doc.replace(/\*\*(\S(.*?\S)?)\*\*/gm, '<strong>$1</strong>');
});
(credit goes to this answer for the regex.)
Note: I am aware there are similar questions already posted on StackOverflow, but the majority were asked 8-10 years ago and use jQuery. I wonder if a more modern, straightforward approach has come about in the last decade that uses vanilla JS.