I have made a javascript function to replace some words with other words in a text area, but it doesn't work. I have made this:
function wordCheck() {
var text = document.getElementById("eC").value;
var newText = text.replace(/hello/g, '<b>hello</b>');
document.getElementById("eC").innerText = newText;
}
When I alert the variable newText, the console says that the variable doesn't exist.
Can anyone help me?
Edit:
Now it replace the words, but it replaces it with <b>hello</b>, but I want to have it bold. Is there a solution?
If <textarea>
, then you need to use .value
property.
document.getElementById("eC").value = newText;
And, as mentioned Barmar, replace()
replaces only first word. To replace all word, you need to use simple regex. Note that I removed quotes. /g
means global replace.
var newText = text.replace(/hello/g, '<b>hello</b>');
<div id="eC" contenteditable></div>
So then you need to access innerHTML
:
function wordCheck() {
var text = document.getElementById("eC").innerHTML;
var newText = text.replace(/hello/g, '<b>hello</b>');
newText = newText.replace(/<b><b>/g,"<b>");//These two lines are there to prevent <b><b>hello</b></b>
newText = newText.replace(/<\/b><\/b>/g,"</b>");
document.getElementById("eC").innerHTML = newText;
}