Short version:
I have a contenteditable div. I want to delete the last x-characters before cutting the text.
Long version:
If someone types [in a contenteditable div, an autoload list populated with an ajax call should appear. This is already working. I can also insert the selected sentence into the carret position and add ]. But characters already entered by the user must be deleted before adding the sentence. A bracket [is not only a trigger-char, but also a format element similar to a method.
Example:
The text in the div ("|" means carret): Lorem ipsum| sit lorem ipsum dolor
User now enters [doto start automatic suggestion:Lorem ipsum [do| sit lorem ipsum dolor
dolor proposed and inserted after carret: Lorem ipsum [do|dolor sit lorem ipsum dolor
Problem: All pre-made characters domust be deleted before inserting a sentence
Desired behavior: Lorem ipsum [dolor] sit lorem ipsum dolor
Attempted Solution:
Paste text into the cursor in the content edable editor - it works, but I can’t delete the last characters
https://developer.mozilla.org/en-US/docs/Web/API/Selection - tried to get some ideas from MDN, but I don’t know how to change selection textNode content
Code:
Extract the line between the last "[" and carret to search for sentences in the database:
var sel = window.getSelection();
var cords = getCaretCoords();
var searchQuery = extractSearchQuery(sel.anchorNode.data, sel.anchorOffset, "[");
function extractSearchQuery(searchString, caretPos, triggerString) {
searchString = searchString.slice(searchString.lastIndexOf(triggerString) + 1, caretPos);
return searchString;
}
Insert the sentence after the caret:
function insertTextAtCursor(text) {
var sel, range, html;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var newTextNode = document.createTextNode(text);
range.insertNode(newTextNode);
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().text = text;
}
}