Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

340
Views
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 answers
Answer question

0

Try using below code

const newText=text.replace(subString, "[][]");
contenteditable.textContent=newText;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!