首页 > 解决方案 > 如何替换 contenteditable div 中的文本?

问题描述

在互联网上进行研究后,我找不到适合我的问题的答案。所以我有一个内容可编辑的 div 并且字符串的替换方法不起作用。所以我的想法是我想用任何东西(“”)替换子字符串。subString 只是一个短语,而不是 div 中的整个文本。但是字符串的replace方法没有做任何事情,我尝试调试它但没有运气。newTask() 在这个可内容编辑的 div 中创建另一个 div,因此它可能会改变结果。

这是代码:

var bodyText = document.querySelector(".textarea");

bodyText.addEventListener("keypress", () => {
    var key = window.event.keyCode;
    if (key === 13) {
        var contenteditable = document.querySelector("[contenteditable]");
        var text = contenteditable.textContent;

        var subString = text.substring(
            text.indexOf("!") + 1,
            text.lastIndexOf("!")
        ); //gets specific phrase
        // 'subString' phrase is also the thing i wanted it to be replaced

        const string = subString;
        if (subString !== "") {
            console.log(string);
            newTask(string);
            text.replace(subString, "[][]"); //<--this does not work
        }

    }
});

function newTask(input) {
    var taskDiv = document.createElement("div");
    taskDiv.className = "task";
    taskDiv.addEventListener("click", () => {
        taskDiv.classList.toggle("completed");
    });

    var textboxDiv = document.createElement("div");
    textboxDiv.className = "textbox";
    textboxDiv.contentEditable = true;
    textboxDiv.innerHTML = input;

    taskDiv.appendChild(textboxDiv);
    bodyText.appendChild(taskDiv);
}

问我是否需要更多信息。感谢您的帮助!

标签: javascripthtml

解决方案


尝试使用下面的代码

const newText=text.replace(subString, "[][]");
contenteditable.textContent=newText;

推荐阅读