javascripthtmlcss

How to style a specific word in textarea


I have something like this in my code (I can't put too much code in StackOverFlow):

 <textarea id="text" style="width:500px;height:500px;">
    Have I Cherry
    Have I Banana
    Have I Apple
    Have I Banana
    Have I Strawberry
    </textarea>

On my script I fixed the orders already so it turns in to this.

 <textarea id="result" style="width:500px;height:500px;">
I Have Cherry
I Have Banana
I Have Apple
I Have Banana
I Have Strawberry
</textarea>

What I want is if the word is Banana, style= yellow, else style = red. This is what I tried

lines = text.value.split('\n');
result.value = '';
for(var i = 0;i < lines.length;i++){
    var line = lines[i];
    var word = line.split(' ');
     var check = line.match(/Banana/);
     if(check) {
    result.value += word[1] + ' ' + word[0] + ' ' + word[2].style.color = "yellow";

Result should be every Banana word is yellow and other is red. Remember not the whole sentence should be yellow, only 'Banana'. Is there any way I can do this?


Solution

  • Textarea is not the best way to do what you want, try using a div with editable content, you'll have more control over the styling.

    That way you'll be able yo wrap all bananas in a <span style="color: yellow">.