The only thing I'm not happy about is how it handles line breaks and tabs.
It's a tiny bit more complex than only replacing red, but this way you can highlight any word in any color and probably even mix several of these on the same element, so the functions used are reusable.
<html>
<head>
<style>
#myTextarea {
border: 1px solid black;
border-radius: 5px;
min-height: 50px;
width: 50%;
}
.hl-red {
color: red;
}
</style>
</head>
<body>
<div id="myTextarea" contenteditable>Test string</div>
<script>
var createHighlighter = function createHighlighter( word ) {
// Let's create a reusable function that can highlight any word.
// You call this function providing the word you want highlighted.
// Then this returns a function that will insert some html spans around each instance of the word.
// You can the call the returned function with any string to get the string saturated with the span tags.
return function highlight( str ) {
// We split on the word we want to highlight, so our array contains all the non-highlighted chunks.
// Since we can call the function multiple times in a row, we will usually want to remove the previous highlights, so we don't double-highlight it.
// This can be easily done with a simple global replace regex.
var chunks;
if (str === '<br>') return '';
else {
chunks = str.replace(/\<span\sclass="hl-red"\>/g, '').replace(/\<\/span\>/g, '').split(word);
// Then we add the non-highlighted text + the <span> + the highlighted word.
return chunks.reduce(function( html, chunk, index ) {
html += chunk;
// Add the highlighted word, except for the last chunk, since that's just the end of the string.
if ((index + 1) !== chunks.length) html += '<span class="hl-red">' + word + '</span>';
return html;
}, '');
}
};
};
var wordToHighlight = 'red';
var highlightRed = createHighlighter( wordToHighlight );
var highlightArea = function highlightArea( event ) {
event.target.innerHTML = highlightRed( event.target.innerHTML );
};
document.querySelector('#myTextarea').addEventListener('keyup', highlightArea);
</script>
</body>
</html>