I have two textareas written in HTML like this:
<textarea id="checked-words"></textarea>
<br />
<textarea id="words" onkeyup="displayColoredText()"></textarea>
<div id="text-to-insert"></div>
(into the div
element, I will insert text, using JavaScript
)
My task is to write into the div
section the text from the second textarea
and make red the occurrences of strings from the first textarea
.
Example
If the first textarea
contains the following words: aaa
, aab
and the second contains aaab
, all of the characters have to be red. If the second one contains abaa, none of the characters will be red in the div
section.
Here is my JavaScript
function which displays and colorize the text:
function displayColoredText() {
//Displays the colored text below the second textarea
//Find the two textareas
var firstTextArea = document.getElementById('checked-words');
var secondTextArea = document.getElementById('words');
//Split by spaces
var checkedWords = firstTextArea.value.split(" ");
var text = secondTextArea.value.split(" ");
var textToInsert = secondTextArea.value;
for(i in checkedWords) {
console.log(checkedWords.length);
textToInsert = textToInsert.replace(new RegExp(checkedWords[i], 'g'), '<span class="insertRed">' + checkedWords[i] + '</span>');
}
document.getElementById('text-to-insert').innerHTML = textToInsert;
}
My problem is, that an already replaced text won't be considered, for example, if the first textarea
contains aaa
and aab
and if the second one contains aaab
, only the first three characters will be red, instead of the whole string. How can I resolve this?