replace selected text in contenteditable div
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>
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;
}
}
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);