Issue
I'm trying to create a function that can read through large a string of text, automatically detect keywords, 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 keywords 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 keywords, 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.
Solution
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 :
- we can have a method getWordAndColor for set color to word
- We can have another method to change the sentence word to specified color
const getWordAndColor = () => {
let wordAndColor = {};
wordAndColor['he'] = 'green';
wordAndColor['walked'] = 'red';
wordAndColor['store'] = '#4682B4';
return wordAndColor;
}
const setColorToWord = (wordAndColor, sentence) => {
for (let key in wordAndColor) {
if (wordAndColor.hasOwnProperty(key)) {
let value = wordAndColor[key];
let dynamicPattern = key;
let pattern = new RegExp("\\b" + dynamicPattern + "\\b", 'gi');
let replacement = '<span style="color: '+value+';">'+key+'</span>';
sentence = sentence.replace(pattern, replacement);
}
}
return sentence;
}
let sentence = "he walked to the store and then he walked to his house,";
let wordAndColor = getWordAndColor();
document.getElementById('wordAndColorText').innerHTML = setColorToWord(wordAndColor, sentence);
<div id="wordAndColorText"></div>
Answered By - Sahab
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.