I want to display text message conversations in my chat app.
My case: When user search some text in search box, message include searchText will be style with red color. Example:
user search: "div"
// messageText = "abc <div>all is text</div>" (searching in plain text here);
// htmlText = "abc <div>all is text</div>";
// OUTPUT MUST BE: "abc <<span style='color: red'>custom</span>>string <<span style='color: red'>custom</span>>"
Here is my code:
const origin = "abc <div>all is text </div>"; // text input
const str = "abc <div>all is text </div>"; // after sanitize
const element = document.createElement("div");
element.innerHTML = str;
for (let node of element.childNodes) {
// I want replace "div" text with my custom html
node.textContent = node.textContent.replace(/div/gi, "<span style='color: red'>custom</span>");
}
const result = element.innerHTML;
console.log(result);
Here is the result
output
Output
abc <<span style='color: red'>custom</span>>string </<span style='color: red'>custom</span>>
Expect
abc <<span style='color: red'>custom</span>>string <<span style='color: red'>custom</span>>
Can you help me, tks for your help.