0

so all the tutorials on replacing words for Google Chrome gives me something like this -

var replacedText = text.replace(/(hello)/gi, "goodbye");

if (replacedText !== text) {
    element.style.color = colour;
    element.replaceChild(document.createTextNode(replacedText), node);

}

So I understand that the data I receive is a sentence and I can specifically replace words and update the sentence. What I want to achieve is to turn singular words to a different colour. Right now it will change the entire sentence to red.

Does anyone know how to do this?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • You should take a look at [ask] and [MCVE] and add more detail to your question so others can replicate the or at least understand the problem you are running into. – pvg Sep 05 '17 at 21:26
  • Related/duplicate: [Change matching words in a webpage's text to buttons](https://stackoverflow.com/q/40572679), [Replace text with link with chrome extension](https://stackoverflow.com/q/40276158), [Highlight a word of text on the page using .replace()](https://stackoverflow.com/q/40710728) – Makyen Sep 06 '17 at 02:07

1 Answers1

1

the text to be colored needs to be wrapped in a span:

this is a test

and you need to add the following:

this is a <span style="color:red">test</span>

Within your conditional you could do the following:

text.replace(/(\YOUR_WORD)\s/g, "<span style="color:red">$1</span> ")
ren.rocks
  • 772
  • 1
  • 7
  • 22