mardi 16 novembre 2021

I want to change the color of the words if we find it on give array

I'm working on a project and I want to change the text color of a given word if we find it on an array. as an example, I have an array ["Lorem","nemo"] and the text that I'm getting is from the body tag

this is my index file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body id="body">
    
    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore sed sequi quos veniam? Cum consectetur exercitationem maxime, aperiam saepe reprehenderit fuga ipsa labore rerum ex error fugiat quasi accusantium nemo.
    </div>


    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore sed sequi quos veniam? Cum consectetur
        exercitationem maxime, aperiam saepe reprehenderit fuga ipsa labore rerum ex error fugiat quasi accusantium nemo.
    </div>

    <div>
        Here, we have used a regular expression to match a certain portion of the string. We can capture certain groups in the
        match using matchAll() better than match().
    </div>
   

    <script src="main.js"></script>
</body>
</html>

and this is my javascript


function change(){
var text =  document.querySelector("body");

var string = text.innerHTML;
// let searching = ["Lorem", "nemo","amet","better","matchAll"];
let searching = ["Lorem","nemo"];

// search
for(search of searching){
    
    var textfind = string.matchAll(search)
    for(m of textfind){
        // console.log(m[0])
        let statring_index  = m.index;
        let ending_index = m[0].length;

        let giventext = string.substring(statring_index, statring_index+ending_index)
        console.log(giventext)
       
        // giventext =  giventext.replace("/"+m[0]+"/g","<span style='color:red';>"+ giventext + "</span>")
       
               
        // document.write("<span style='color:red;>"+ m[0] + "</span>")
        var redText = string.substring(statring_index, statring_index+ending_index);
        text.innerHTML = string.substring(0,statring_index)+"<a style='color:red;'>"+redText+"</a>"+string.substring(statring_index+ ending_index);

    }
    
}
}

change()

Now the problem, I'm getting is that I want all the occurrences to be in red color but my code is only able to change the last element in the array just once

output of the code

So what I want to change all the occurrences to the red color if we have that word in a searching array




Aucun commentaire:

Enregistrer un commentaire