I am trying to create a text editor where users can highlight parts of their input from a content editable div and style it. I used indexes and substring method to modify only the highlighted text.
For example, if the input is "helloworld" and they highlight "owo". The re-created text would be
"hell" + <span>owo</span> + "rld" and add styling to that span. However, if the user tries to edit the text again, my indexes gets messed up because now the text I am getting is
"hell<span>owo</span>rld" instead of "helloworld". I believe this indexing and substring method is not ideal for this kind of problem. Can someone suggest a different method I should try?
Below is my code for getting the selected indexes and replacing the text inside the div.
//function to get indexes of the highlighted text
function getSelectionIndexes() {
var start, end;
if(window.getSelection){
start = window.getSelection().anchorOffset;
end = window.getSelection().focusOffset;
}
return {
start: Math.min(start,end),
end: Math.max(start,end),
selectedText: window.getSelection().toString()
};
}
//function to re-format the text and insert it into the div content
function replaceText(className){
const text = $('#textarea').html();
const { start, end, selectedText} = getSelectionIndexes();
if(start == end) return;
const beforeText = text.substring(0,start);
const afterText = text.substring(end);
const beforeElement = document.createElement("span");
beforeElement.innerHTML = beforeText;
const selectedElement = document.createElement("span");
selectedElement.innerHTML = selectedText;
selectedElement.classList.add(className);
const afterElement = document.createElement("span");
afterElement.innerHTML = afterText;
$('#textarea').html('');
$('#textarea').append(beforeElement);
$('#textarea').append(selectedElement);
$('#textarea').append(afterElement);
}