Search code examples
javascripthighlight

How can I can highlight words that are more or equal to 8 characters in paragraph? JavaScript


I am trying to highlight the words that are equal or greater than 8 characters from the paragraph. I tried to put some code from other sources but it doesn't work. Here is the code:

enter code here
let txt=document.createElement("p").innerText;

 function highlightWords() {
     let words = txt.split(" ");
     let size = 8
     for (let i = 0; i < words.length; i++) {
         let word = words[i];
         let processedP = "<p>";
         if (index>=8) {
             innerText=innerText.substring(0,index)+ "<span class='lightext'>"+innerText.substring(index,index+txt.length)+ "</span>" + innerText.substring(index + txt.length);
         } else {
         }

         return txt;

     }
 }

 highlightWords();

JsBin my web


Solution

  • You had many of the right pieces there, just needed to put them together a bit differently.

    I have put together a complete HTML that has it all working together, with some comments on how things are working.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            .lightext {
                background-color: yellow;
            }
        </style>
    </head>
    <body>
        <p id="targetp">This is the extremely long paragraph that we want to highlight all words longer than eight characters in.</p>
    <script>
    
    
    function highlightWords() {
        const txt = document.getElementById("targetp").innerText;
        let output = "";
        let words = txt.split(" ");
        let size = 8   //don't really need this - size as a variable isn't used anywhere else,
        let replacementword = ""; //this will store our output - it's easier than trying to update thee text "in place"
        for (let i = 0; i < words.length; i++) {
            let word = words[i];
            if (word.length >= 8) {  //this is where we figure out if the word is longer than 8
                replacementword = "<span class='lightext'>" + word + "</span>";  //if it is, we just need to wrap it in a span with lighttext class - assuming you have a "highlighted" style applied to class lightext, see styles above for mine
            } 
            else {
                replacementword = word;  //shorter than 8, don't need to change anything
            }
            output = output + " " + replacementword + " ";  //add the updated word to our output
        }
    
        return output; //return our finished output string to the function call
    }
    
    document.getElementById("targetp").innerHTML = highlightWords();   //actually update the <p> tag with the new text, WHICH is now HTML rather than just plain text
    </script>
    
    </body>
    </html>