Search code examples
javascripthtmlcsscontenteditable

How can I color specific words on content editable element?


I am trying to make a coding editor, my problem is I want to color specific words on a content editable div for example if the user wrote this code: function print(){}; function load(){}; the word "function" should be colored red.

Here's what I have tried, unfortunately it does not work but I wanted to show effort and the idea of what I'm trying to accomplish.

let editor = document.getElementById("editor");

editor.oninput = () => {
    editor.innerHTML = colorWord(editor.innerHTML, "function");
    caretAtEnd(editor);
}

function colorWord(text, word) {
    while (text.includes(word)) {
        text = text.replace(word, "<span style='color:blue;'>" + word + "</span>");
    }
    return text;
}

function caretAtEnd(element) {
    element.focus();
    if (typeof window.getSelection != "undefined" &&
        typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(element);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(element);
        textRange.collapse(false);
        textRange.select();
    }
}

Solution

  • Your problem is your while loop. If word is in the text, text will always include word (since you are just adding to the string) and your while loop will never end. Simply change it to an if

    function colorWord(text, word) {
        if (text.includes(word)) {
            text = text.replace(word, "<span style='color:blue;'>" + word + "</span>");
        }
        return text;
    }