I’m trying to create a function that can read through large a string of text, automatically detect key words, and then change the color of these individual words. For example, in the sentence, "he walked to the store and then he walked to his house," I want the function to individually detect the word "he" and change the text color to green, while also detecting the word "walked" to change the text color to red without altering the rest of the sentence. This would be on a much greater scale with more key words and colors.
I’ve gotten to the point where I can get my program to detect certain words in a string of text written in a or , but when I attempt to change the color of the words through there, it changes the color of all of the words in the string (by altering the css), which isn’t what I want. I also got it to change the individual word within a , but it changed the words within other sections as well.
I’m also having difficulty getting it to change the different key words, for example when it uses the color green for "walked" when it should actually be red. I don’t want to manually use around every single word, so I would like to find a way to do this automatically.
I appreciate any assistance, thank you!
3
Answers
Try this example.
this function to individually detect the word "he" and change the text color to green, while also detecting the word "walked" to change the text color to red without altering the rest of the sentence.
For pure javascript, you can do this
In the snippet, input word that need to be changed to ‘green’ and ‘yellow’. Then press
Submit
To actual change a word color inside a string, you need to wrap it inside a
<span/>
. Then change that<span/>
CSS onlychangeColor
method will wrap specific word inside<span/> and change it color, then return the styled string. Then you can put this styled string in
element.innerHTML`Let see why may have problem with your approach:
Your pattern may not match whole word that why it changed the words within other sections as well.
you does not have color assign approach
How we can fix it :