Search code examples
javascriptregexreplacewords

Replace words of text area


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?


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


    But if you want to really bold your text, you need to use content editable div, not text area:

    <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(/&lt;b&gt;&lt;b&gt;/g,"&lt;b&gt;");//These two lines are there to prevent <b><b>hello</b></b>
        newText = newText.replace(/&lt;\/b&gt;&lt;\/b&gt;/g,"&lt;/b&gt;");
        document.getElementById("eC").innerHTML = newText;
    }