2

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'. Still new to Javascript, can anyone tell me if there's anyway I can do this?

Elliot
  • 73
  • 8

1 Answers1

2

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

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content

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

izambl
  • 629
  • 3
  • 9
  • I still don't know how to do it in a div without styling the whole sentence into the same color . There would be 2 div and the result one is what I want to change color. – Elliot Feb 15 '20 at 02:06
  • Plus this actually hide my results when I change the textarea to a div and launch it. It seems like I can't result.value += in a div a something. – Elliot Feb 15 '20 at 02:22
  • `element.innerHTML = element.innerHTML.replace('Banana', 'Banana');` will only replace the first ocurrence – izambl Feb 15 '20 at 02:25
  • Being a div you'll have to use .innerHTML or .innerText instead of .value – izambl Feb 15 '20 at 02:26
  • Thanks, I did " – Elliot Feb 15 '20 at 04:48