Home > Software engineering >  I want to change the color of the words if we find it on give array
I want to change the color of the words if we find it on give array

Time:11-16

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

CodePudding user response:

  • 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;

CodePudding user response:

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 >${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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related