You can use the save and restore feature module in Rangy , which uses invisible marker elements at the selection borders. I also suggest replacing after a certain period of inactivity, and not on every event keyup:
function formatText(el) {
var savedSel = rangy.saveSelection();
var text = el.innerHTML.replace(/this/gm, "<i>this</i>");
el.innerHTML = text;
rangy.restoreSelection(savedSel);
}
var keyTimer = null, keyDelay = 500;
document.getElementById('div1').onkeyup = function() {
if (keyTimer) {
window.clearTimeout(keyTimer);
}
keyTimer = window.setTimeout(function() {
keyTimer = null;
formatText(document.getElementById('div1'));
}, keyDelay);
};
source
share