skip to Main Content

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


  1. 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.

    <html lang="en">
    <head>
    
      <title>Coloring Words</title>
      
      <!-- Include jQuery from a CDN (Content Delivery Network) -->
      <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
      
    </head>
    <body>
      <div id="coloredText">he walked to the store and then he walked to his house</div>
     
    </body>
    </html>
    
    .green {
      color: green;
    }
    
    .red {
      color: red;
    }
    
    $(document).ready(function() {
      var coloredText = $("#coloredText").text();
      var keywordClasses = {
        "he": "green",
        "walked": "red",
       
      };
      var words = coloredText.split(/s+/);
    
     
      for (var i = 0; i < words.length; i++) {
        var word = words[i].toLowerCase(); // Convert to lowercase for case-insensitivity
        var cssClass = keywordClasses[word];
        if (cssClass) {
          words[i] = "<span class='" + cssClass + "'>" + words[i] + "</span>";
        }
      }
    
     
      $("#coloredText").html(words.join(' '));
    });
    
    Login or Signup to reply.
  2. For pure javascript, you can do this

    // Original string
    const original = 'he walked to the store and then he walked to his house,'
    // Set original string
    document.querySelector("#original").innerText = original
    
    // On form submit
    document.querySelector("form").addEventListener("submit", onSubmit)
    // On form submit handler
    function onSubmit(event) {
      event.preventDefault()
      // Styled output
      let output = original
      
      // Get text to be converted to green
      const greenText = document.querySelector("#toGreen").value
      // Get text to be converted to yellow
      const yellowText = document.querySelector("#toYellow").value
    
      // Change all `greenText` to green and return
      output = changeColor(output, greenText, 'green')
      // Change all `yellowText` to yellow and return
      output = changeColor(output, yellowText, 'yellow')
    
      // Print styled string to screen
      document.querySelector("#styled").innerHTML = output
    }
    
    function changeColor(string, text, color) {
      return string.replace(text, `<span style="color: ${color}">${text}</span>`)
    }
    <form>
      <label for="fname">To green:</label>
      <input type="text" id="toGreen"><br><br>
      <label for="lname">To yellow:</label>
      <input type="text" id="toYellow"><br><br>  
      <input type="submit" value="Submit">
    </form>
    
    <h3>Original</h6>
    <div id="original"> he walked to the store and then he walked to his house,</div>
    <h3>After</h6>
    <div id="styled"> he walked to the store and then he walked to his house,</div>

    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 only

    changeColor 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`

    Login or Signup to reply.
  3. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search