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!
Try using below code
const newText=text.replace(subString, "[][]");
contenteditable.textContent=newText;