How do i change to color of specific characters in a text using javascript?

412 Views Asked by At

So I have 2 textareas. In the first one, I have keywords and in the second one, I have the text. I want to change the color of every appearance of the keywords in the text to red and I have to do it in real-time. Like so: enter image description here

Now the problem is whit this: enter image description here

This is my code so far:

HTML

<textarea id="filter" cols="50" rows="20"></textarea>
<textarea id="text" cols="50" rows="20" onkeyup="writeText()"></textarea>
<p id="showText"></p>

CSS

.colorText {
    color: red;
}

JS

function writeText() {
    let text = document.getElementById("text").value;
    let filters = document.getElementById("filter").value.split(' ');

    for(var i=0; i<filters.length; i++) {
        var regex = new RegExp(filters[i], 'g');
        text = text.replace(regex, `<span class="colorText">${filters[i]}</span>`);
    }

    document.getElementById("showText").innerHTML = text;
}

Any ideas on how I can fix this?

0

There are 0 best solutions below