如何为内容可编辑元素上的特定单词上色?

我正在尝试编写代码编辑器,我的问题是,例如,如果用户编写了以下代码,我想给内容可编辑div上的特定单词上色: function print(){}; function load(){};“功能”一词应涂成红色。

这是我尝试过的方法,很遗憾,它不起作用,但我想展示自己的努力以及我要实现的目标。

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();
    }
}
fightgod100_01 回答:如何为内容可编辑元素上的特定单词上色?

您的问题是您的while循环。如果文字中包含单词,则文字将始终包含word(因为您只是添加到字符串中),并且while循环将永远不会结束。只需将其更改为if

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

,

您的函数colorWord(text,word)永远不会前进到下一个单词,实际上,这已经是一个无限的while循环。 .includes将始终找到第一个实例,并且由于您的代码在替换时仍包含单词,因此永远不会前进。

但是,如果使用正则表达式,则可以是全局替换。正则表达式和string.replace是您要寻找的:

function colorWord(text,word) {
  const re = new RegExp(word,'gi'); // this will output /word/gi,with 'word' being whatever value the parameter is
  return text.replace(re,`<span style='color:blue;'>${word}</span>`);
}

console.log(
  colorWord('apples are round,and apples are juicy.','apples')
)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

本文链接:https://www.f2er.com/2911312.html

大家都在问