replace selected text in contenteditable div

JavascriptContenteditable

Javascript Problem Overview


I have been looking high and low for an answer but failed.

Is there a cross-browser solution to replace selected text in contenteditable div?
I simply want users to highlight some text and replace the highlighted text with xxxxx.

Javascript Solutions


Solution 1 - Javascript

The following will do the job in all the major browsers:

function replaceSelectedText(replacementText) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementText));
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.text = replacementText;
    }
}

Solution 2 - Javascript

As I posted a working example on how to add emoji in between the letters in contentEditable div? , you can use this for replacing the needed text in content editable div

  function pasteHtmlAtCaret(html) {
        let sel, range;
        if (window.getSelection) {
          // IE9 and non-IE
          sel = window.getSelection();
          if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // non-standard and not supported in all browsers (IE9, for one)
            const el = document.createElement("div");
            el.innerHTML = html;
            let frag = document.createDocumentFragment(),
              node,
              lastNode;
            while ((node = el.firstChild)) {
              lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
              range = range.cloneRange();
              range.setStartAfter(lastNode);
              range.collapse(true);
              sel.removeAllRanges();
              sel.addRange(range);
            }
          }
        } else if (document.selection && document.selection.type != "Control") {
          // IE < 9
          document.selection.createRange().pasteHTML(html);
        }
      }

      function addToDiv(event) {
        const emoji = event.target.value;
        const chatBox = document.getElementById("chatbox");
        chatBox.focus();
        pasteHtmlAtCaret(`<b>${emoji}</b>`);
      }
      function generateEmojiIcon(emoji) {
        const input = document.createElement("input");
        input.type = "button";
        input.value = emoji;
        input.innerText = emoji;
        input.addEventListener("click", addToDiv);
        return input;
      }
      const emojis = [
        {
          emoji: "😂",
        },
        {
          emoji: "❤️",
        },
      ];
      emojis.forEach((emoji) => {
        document
          .getElementById("emojis")
          .appendChild(generateEmojiIcon(emoji.emoji));
      });

      #emojis span {
        cursor: pointer;
      }
      #chatbox {
        border: 1px solid;
      }

 <button
  type="button"
  onclick="document.getElementById('chatbox').focus(); 
  pasteHtmlAtCaret('<b>INSERTED</b>'); "
>
  Paste HTML
</button>
    <div id="emojis"></div>
    <div id="chatbox" contenteditable></div>

Solution 3 - Javascript

I needed to replace text nodes, and keep html entities when pasting back. This is how I solved the problem, not sure about data in textnodes, maybe it's better to use textContent or something else

let selection = window.getSelection()
  , range = selection.getRangeAt(0)
  , fragment = range.extractContents();

fragment.childNodes.forEach( e => e.data && (e.data = doSomething(e.data)) );
range.insertNode(fragment);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJudyView Question on Stackoverflow
Solution 1 - JavascriptTim DownView Answer on Stackoverflow
Solution 2 - JavascriptSeyyedKhandonView Answer on Stackoverflow
Solution 3 - JavascriptkillovvView Answer on Stackoverflow