Short version:
I have a contenteditable div. I want to remove the last x chars before carret postion.
Long version:
If someone types a [
in the contenteditable div there should appear an autosuggest list, filled by an ajax call. This is allready working. I can also insert the selected suggestion at carret position and add a ]
. But the chars, already typed by the user, should be deleted before appending the suggestion.
The bracket [
is not only the "trigger-char" but also a markdown-like format element.
Example:
Text in the div ("|" stands for carret): Lorem ipsum| sit lorem ipsum dolor
User now types [do
to start auto suggestion: Lorem ipsum [do| sit lorem ipsum dolor
dolor
is suggested and inserted after carret: Lorem ipsum [do|dolor sit lorem ipsum dolor
Problem: the allready typed chars do
should be removed before inserting the suggestion
Desired behaviour: Lorem ipsum [dolor] sit lorem ipsum dolor
Attempted Solutions:
Insert text at cursor in a content editable div - working but i can't remove the last chars https://developer.mozilla.org/en-US/docs/Web/API/Selection - tried to get some ideas from MDN, but no idea how to change the selection's textNode's content
Code:
Extract the string between last "[" and carret to search for suggestions in DB:
var sel = window.getSelection();
var cords = getCaretCoords();
var searchQuery = extractSearchQuery(sel.anchorNode.data, sel.anchorOffset, "[");
function extractSearchQuery(searchString, caretPos, triggerString) {
//cut everything after carret
searchString = searchString.slice(searchString.lastIndexOf(triggerString) + 1, caretPos);
return searchString;
}
Insert the suggestion after carret:
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;
}
}