Is there any way to format a whole line when finding word on page

1

  • Colors & Neutral

If highlight of the others, let's say some simple phrases like:

Cores do Arco-Íris

Cores sortidas

Diversas cores e sabores

Sem cor, apenas Neutro

Preto-e-Branco, neutro

Sabão neutro

Well, these lines should be in " bold " since it contains the words Colors & Neutral .

I've bet my chips on this routine:

var negrito = "cores";
var indexar = string.indexOf(negrito);
if (indexar != -1) {
    // se for diferente de -1 é que a palavra foi localizada então faça uma ação
    ..style.fontWeight='bold';
}
    
asked by anonymous 24.06.2018 / 16:07

2 answers

2

One way is to include everything in a <span> to have a reference and separate the lines with \n , then make a filter and include the <b></b> tags in the text that contains the desired words (explanations in the code).

var negrito = document.querySelector("body span").textContent // pega o texto da span
.split('\n') // converte em array pela quebra de linha
.filter(function(v){ // descarta valores vazios
   return v;
})
.map(function(v){
   if(/cores|neutro/.test(v.toLowerCase())){ // verifica as duas palavras sem diferenciar maúsculo e minúsculo
      v = '<b>'+v+'</b>'; // concatena negrito
   }
   return v; // retorna o valor
})
.join('<br>'); // converte em string com quebra de linha

 document.querySelector("body span").innerHTML = negrito; // substitui o conteúdo da span
<span>
   Cores do Arco-Íris
   Cores sortidas
   Diversas cores e sabores
   Sem cor, apenas Neutro
   nada aqui
   Preto-e-Branco, neutro
   Sabão neutro
</span>
    
24.06.2018 / 20:20
1

Dude, I made an example here, just to give you an idea, because I did not quite understand where the paragraphs are that you do the match. I used the includes () method to look up the occurrence in the paragraph and made a for to go through all the paragraphs. I hope you at least have an idea.

var pTag = document.getElementsByTagName("p");
var i;

for(i=0; i<pTag.length; i++) {
  var p = pTag[i].textContent;
  var cores = p.includes("Cores");
  var neutro = p.includes("Neutro");

  if(cores || neutro) {
    document.getElementsByTagName("p")[i].style.fontWeight = "bold";
  } else {
    document.getElementsByTagName("p")[i].style.color = "red";
  }
}
<p>Cores do Arco-Íris</p>
<p>Cores sortidas</p>
<p>Diversas cores e sabores</p>
<p>Sem cor, apenas Neutro</p>
<p>Preto-e-Branco, neutro</p>
<p>Sabão neutro</p>
    
24.06.2018 / 16:57