How to highlight/highlight words in text?

Asked

Viewed 814 times

-1

Searching Google, about highlighting and/or highlighting words in a text

I found a code that applies this effect called highlight in the search words. However, when I went to test the code, the words were not being highlighted, but analyzing the code I could not find the reason for the problem!

Follow the code below:

function doDestacaTexto(Texto, termoBusca) {

   /*******************************************************************/
   // CASO QUEIRA MODIFICAR O ESTILO DA MARCAÇÃO ALTERE ESSAS VARIÁVEIS
   /*******************************************************************/
   inicioTag = "<font style='color:#000;background-color:#A0FFFF'><b>";
   fimTag = "</b></font>";

   var novoTexto = "";
   var i = -1;
   var lcTermoBusca = termoBusca.toLowerCase();
   var lcTexto = Texto.toLowerCase();

   while (Texto.length > 0) {
      i = lcTexto.indexOf(lcTermoBusca, i + 1);
      if (i < 0) {
         novoTexto += Texto;
         Texto = "";
      } else {
         if (Texto.lastIndexOf(">", i) >= Texto.lastIndexOf("<", i)) {
            if (lcTexto.lastIndexOf("/script>", i) >= lcTexto.lastIndexOf("<script", i)) {
               novoTexto += Texto.substring(0, i) + inicioTag + Texto.substr(i, termoBusca.length) + fimTag;
               Texto = Texto.substr(i + termoBusca.length);
               lcTexto = Texto.toLowerCase();
               i = -1;
            }
         }
      }
   }
   return novoTexto;
}

function doDestacaTextoBusca(textoBusca, textoObj, ehFrase) {
   if (ehFrase) {
      arrayBusca = [textoBusca];
   } else {
      arrayBusca = textoBusca.split(" ");
   }

   var Texto = textoObj.innerHTML;

   for (var i = 0; i < arrayBusca.length; i++) {
      Texto = doDestacaTexto(Texto, arrayBusca[i]);
   }
   textoObj.innerHTML = Texto;
   return true;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
   <head>
      <title>Highlight de Textos igual ao Google</title>
      <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1" />
      <head>
         <script language="JavaScript" src="destacaTexto.js"></script>
   </head>
   <body>
      Escolha a palavra: 
      <input type="text" value="codigo" size="25" name="busca">
      <input type="button" onClick="doDestacaTextoBusca(document.getElementById('busca').value, teste)" value="Destacar Texto"><br>
      <br />
      <div id="teste">
         Site para programadores com codigos fonte, noticias, video aulas, downloads, artigos e tutorias. Tudo sobre Web. ASP, PHP, .NET, JSP, ABAP, JavaScript, ActionScript DHTML, XHTML, CSS, Web Standards/Tableless, mySQL, SQL, Photoshop, Flash MX e muito mais.
         Utilize a palavra "codigo" como exemplo pois há neste texto muitas repetições de codigo, assim é possível ver a palavra codigo em destaque diversas vezes.
      </div>
   </body>
</html>

Source: https://www.codigofonte.com.br/codigos/efeito-hightlight-em-palavras-igual-ao-google

  • It wasn’t clear what you’d like to do?

  • Hello @Renan, I changed the initial question to clarify my question.

2 answers

2

You can use the markjs for this:

// cria uma instância definindo o elemento onde será "marcada" as palavras.
var instance = new Mark(document.getElementById('source'))

function highlight(word){
  instance.unmark({
    done: function(){
      instance.mark(word)
    }
  })
}

document
  .getElementById('query')
  .addEventListener('input', function(){
    highlight(this.value)
})
<script src="https://cdn.jsdelivr.net/mark.js/8.6.0/mark.min.js"></script>

<input id='query' placeholder='Buscar por...' type='text'>

<div id='source' contenteditable>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sollicitudin, purus ac tempus faucibus, dolor ligula tempus lectus, a vulputate dolor lorem at nibh. Praesent euismod metus ante. Maecenas sit amet magna eget mauris lobortis semper nec vel dolor. Maecenas at turpis vel lectus suscipit posuere sed id tortor. Sed tristique viverra dolor, vitae semper elit fermentum et. Quisque dignissim neque at molestie finibus. Mauris porttitor leo nec velit lacinia, sed gravida mi tincidunt. Donec hendrerit eros vel magna hendrerit faucibus.
Suspendisse eu iaculis neque. Nullam quam sem, maximus a nulla eu, gravida pellentesque ipsum. Duis tempus pretium enim, eu accumsan lorem ullamcorper id. Ut tristique risus leo, non venenatis neque facilisis a. Sed vel urna sit amet nisl posuere semper vel non purus. Sed tempus neque quis accumsan vehicula. Phasellus mollis mollis felis. Cras dignissim gravida elit, at aliquam metus lobortis ac. Aliquam ac dapibus justo. Vivamus porttitor commodo magna, ut cursus felis imperdiet id. Aenean placerat nisi vitae justo semper, sit amet tristique tellus tempor.
</div>

If you want to format the hightlight (other colors, etc.) simply style the element mark with CSS, inserting the properties you prefer. Markjs creates an element <mark> for each match found in the element observed by the instance. More information (accuracy, case sensitive, filters, etc.) can be found in project documentation.

Another example, displaying the number pouch data in the text:

// cria uma instância definindo o elemento onde será "marcada" as palavras.
const instance = new Mark(document.getElementById('source'))
const matches = document.getElementById('matches')

function highlight(word){
  instance.unmark({
    done: function(){
      instance.mark(word, {
        done: function(numberOfOccurrences){
          matches.innerHTML = numberOfOccurrences
        }
      })
    }
  })
}

document
  .getElementById('query')
  .addEventListener('input', function(){
    highlight(this.value)
})
div { padding: 5px; margin-top: 2%; border: 1px solid #ccc }
<script src="https://cdn.jsdelivr.net/mark.js/8.6.0/mark.min.js"></script>

<input id='query' placeholder='Buscar por...' type='text'>
Matches: <span id='matches'>0</span>

<div id='source' contenteditable>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sollicitudin, purus ac tempus faucibus, dolor ligula tempus lectus, a vulputate dolor lorem at nibh. Praesent euismod metus ante. Maecenas sit amet magna eget mauris lobortis semper nec vel dolor. Maecenas at turpis vel lectus suscipit posuere sed id tortor. Sed tristique viverra dolor, vitae semper elit fermentum et. Quisque dignissim neque at molestie finibus. Mauris porttitor leo nec velit lacinia, sed gravida mi tincidunt. Donec hendrerit eros vel magna hendrerit faucibus.
Suspendisse eu iaculis neque. Nullam quam sem, maximus a nulla eu, gravida pellentesque ipsum. Duis tempus pretium enim, eu accumsan lorem ullamcorper id. Ut tristique risus leo, non venenatis neque facilisis a. Sed vel urna sit amet nisl posuere semper vel non purus. Sed tempus neque quis accumsan vehicula. Phasellus mollis mollis felis. Cras dignissim gravida elit, at aliquam metus lobortis ac. Aliquam ac dapibus justo. Vivamus porttitor commodo magna, ut cursus felis imperdiet id. Aenean placerat nisi vitae justo semper, sit amet tristique tellus tempor.
</div>

0

According to your specific problem, the error is , simplesmnete, here:

<input type="text" value="codigo" size="25" name="busca">

Replace with:

<input type="text" value="codigo" size="25" id="busca">

You put name="busca", but it must be id="busca".

I put the example here:

https://repl.it/@TaffarelXavier/LatestAustereEfficiency

Browser other questions tagged

You are not signed in. Login or sign up in order to post.