'How to replace words in real time like with Facebooks emoticons (javascript)

I want to replace words with others as soon as you finish typing them like Facebook emoticons. I ran into a few problems though.

var word = 0;
var matches = ['dumb','sucker','idiot'];

document.addEventListener('input', function(e) {
  if (e.target && e.target.id == 'myinput') {
    if (e.data == ':' && word === 0) {
      word = ':';
    }

    if (e.data != ':' && word != 0) {
      word += e.data;
    }

    if (e.data == ':' && word.length > 1) {
      var findit = word.replaceAll(':', '');

      if (matches.indexOf(findit) != -1) {
        var selection = window.getSelection();

        myinput.innerHTML = myinput.innerHTML.replace(word + ':', 'something');
        selection.modify('move', 'forward', 'lineboundary');
      }
      word = 0;
    }
  }
});
<div id="myinput" contenteditable="true"></div>

as you type a word that begins and ends with : it gets replaced at once. Problem is some times you may mistype the word after you have typed the first : and before typing the second one and once you do that you have to delete the whole word and start over instead of just deleting the part that is wrong and complete the word. How can I address that?

Second problem is once you replace the inner html the cursor moves back to the initial position instead of staying where you last typed. I addressed that with selection.modify('move', 'forward', 'lineboundary') but the issue comes when you try to correct something in the middle of the sentence or so because the cursor will now move to the end of it. How can I fix that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source