Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

341
Vistas
How to replace text in a contenteditable div?

After researching on the internet, I couldn't find an answer to fit my issue. So I have a contenteditable div and the replace method of a string does not work. So the idea is that I want to replace the subString with nothing (""). The subString is simply a phrase not the whole text in the div. But the replace method of the string does not do anything, and I tried debugging it but it was no luck. The newTask() creates another div inside this contenteditable div, so it may vary the outcome.

Here is the code:

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);
}

Ask me if you need anymore information. Thanks for thr help!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try using below code

const newText=text.replace(subString, "[][]");
contenteditable.textContent=newText;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda