0

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

iamhimanshu0
  • 369
  • 2
  • 10

3 Answers3

1

Here's what you can do. Didn't checked If it's optimized or not though.

<!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 class="change-color">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore sed sequi quos veniam? Cum consectetur
        exercitationem maxime, aperiam saepe lorem fuga nemo 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>

    <script>
        const searching = ["Lorem", "nemo"];
        const strings = document.querySelectorAll('.change-color').forEach(el => {
            let text = el.innerText;
            searching.map(search => {
                text = text.replaceAll(search, `<span style="color: red;">${search}</span>`);
            });
            // el.innerHTML = text;
            el.innerHTML = text;
            // console.log(el.innerText);
        })

    </script>

</body>

</html>
Ankit
  • 181
  • 2
  • 15
  • i've run this code but at last it's returning ```undefined``` – iamhimanshu0 Nov 16 '21 at 09:34
  • @iamhimanshu0 Try to read understand code. Don't just copy paste. It's my bad that I didn't polish the answer as was in a hurry. Just remove last console. Updated my answer. – Ankit Nov 16 '21 at 09:40
  • 1
    https://stackoverflow.com/a/46019166/9473050 A good reference found. – Ankit Nov 16 '21 at 09:43
1
  • text.innerHTML = string.substring(...) is inside the loop, it updates document body over and over again, and only the last update takes effect.

  • string is immutable, string.substring does not update the string variable instead it returns a new copy. But there is no assignment to new string variable in the code.

Simple replacement could actually work

const searching = ["Lorem","nemo"];
let str = document.querySelector("body").innerHTML;
searching.forEach(term => {
  str = str.replaceAll(term, `<a style="color:red;">${term}</a>`);
});
document.querySelector("body").innerHTML = str;

Case insensitive and match entire word with capturing group

const searching = ["Lorem","nemo"];
let str = document.querySelector("body").innerHTML;
searching.forEach(term => {
  str = str.replace(new RegExp(`(\\b${term}\\b)`, 'gi'), '<a style="color:red;">$1</a>');
});
document.querySelector("body").innerHTML = str;
ProDec
  • 5,390
  • 1
  • 3
  • 12
1

You may find this method easier. It iterates over the div elements, then iterates over the words using a simple regex on that word with replaceAll, finally assigning the HTML back to the div's innerHTML.

const arr = ['Lorem', 'nemo', 'sequi', 'we'];

const divs = document.querySelectorAll('div');

// Iterate over the divs
divs.forEach(div => {

  // Assign the innerText of the current div
  // to a new variable called html
  let html = div.innerText;

  // Now iterate over the words
  arr.forEach(word => {

    // Create a global regex with that word
    const regex = new RegExp(word, 'g');

    // Replace all the instances of that word in the
    // html variable, and assign it back to that variable
    html = html.replaceAll(regex, (match) => {
      return `<span class="red">${match}</span>`;
    });
  });

  // Finally assign the html to back to the div
  div.innerHTML = html;

});
.red { color: red; }
div { margin-bottom: 1em; }
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore sed sequi quos veniam? Cum consectetur exercitationem maxime, aperiam saepe reprehenderit Lorem 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>
Andy
  • 61,948
  • 13
  • 68
  • 95