Find string on page with JavaScript

0

How can I perform a search on a DIV similar to Chrome's Ctrl + F with javascript?

Regardless of uppercase, lowercase, accents, etc.

So far I have the result below. I get the term found and check if there is any occurrence in the text. But when the occurrence has an accent, it does not stand out.

I'm using this script to get the result in the image.

var searchTerm = "CLAUDIA";

var html = $("#texto").text();

var pattern = "([^\w]*)(" + searchTerm + ")([^\w]*)";

var rg = new RegExp(pattern, "gi");

var match = rg.exec(html);

if(match) {

   html = html.replace(rg,match[1] + "<b>"+ match[2] +"</b>" + match[3]);

   $("#texto").text(html);

}

link

    
asked by anonymous 15.02.2018 / 16:07

4 answers

1

In the code I added a function that removes all the accents and converts the text of div as well as the search term to lowercase. This makes it easier to locate the search term in the text.

Then, after the match in the raw text (no accents and lowercase ) I redefined the regex to find and replace the occurrences in the text original the searched term.

See it working:

function tiraAcentos(i){
   
   var i = i.toLowerCase().trim();

   var acentos = "ãáàâäéèêëíìîïõóòôöúùûüç";
   var sem_acentos = "aaaaaeeeeiiiiooooouuuuc";
   
   for(var x=0; x<i.length; x++){
      var str_pos = acentos.indexOf(i.substr(x,1));
      if(str_pos != -1){
         i = i.replace(acentos.charAt(str_pos),sem_acentos.charAt(str_pos));
      }
   }
   
   return i;
}

var searchTerm = "coracao";
var html = $("#texto").text().trim();
var html_limpo = tiraAcentos(html);

var pattern = "([^\w]*)(" + tiraAcentos(searchTerm)+"|"+searchTerm + ")([^\w]*)";
var rg = new RegExp(pattern, "g");
var match = rg.exec(html_limpo);
if(match) {
   var match_pos = html_limpo.indexOf(tiraAcentos(match[2]));
   match[2] = html.substring(match_pos, match[2].length+match_pos);
   rg = new RegExp(pattern.replace(tiraAcentos(searchTerm),match[2]), "g");
   html = html.replace(rg,match[1] + "<b>"+ match[2] +"</b>" + match[3]);
   $("#texto").html(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="texto">
   Acentos são permitidos e até LETRAS MAIÚSCULAS coração e CLÁUDIA coração
</div>
    
16.02.2018 / 17:59
1

Another alternate way I found without using regex was to use while and for . The while takes the positions of the term inside the text raw and then the for makes the substitutions in the original text:

See it working:

function tiraAcentos(i){
   
   var i = i.toLowerCase().trim();

   var acentos = "ãáàâäéèêëíìîïõóòôöúùûüç";
   var sem_acentos = "aaaaaeeeeiiiiooooouuuuc";
   
   for(var x=0; x<i.length; x++){
      var str_pos = acentos.indexOf(i.substr(x,1));
      if(str_pos != -1){
         i = i.replace(acentos.charAt(str_pos),sem_acentos.charAt(str_pos));
      }
   }
   
   return i;
}

var searchTerm = "coracao",
   html = $("#texto").text().trim(),
   html_limpo = tiraAcentos(html),
   posicoes = [],
   posicaoCorrente = html_limpo.indexOf(tiraAcentos(searchTerm));

while (posicaoCorrente != -1) {
   posicoes.push(posicaoCorrente);
   posicaoCorrente = html_limpo.indexOf(tiraAcentos(searchTerm), posicaoCorrente + searchTerm.length);
}

posicoes = posicoes.reverse();

for(var x=0; x<posicoes.length; x++){
   html = html.substring(0,posicoes[x])
   +"<b>"+html.substring(posicoes[x], posicoes[x]+searchTerm.length)+"</b>"
   +html.substring(posicoes[x]+searchTerm.length, html.length);
}

$("#texto").html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="texto">
   Acentos são permitidos e até LETRAS MAIÚSCULAS coracao e CLÁUDIA coração coração
</div>
    
16.02.2018 / 20:16
0

Try this script

<input id="searcher" type="text" name="searcher">


$('#searcher').quicksearch('table tbody tr', {
    'delay': 100,
    'bind': 'keyup keydown',
    'show': function() {
        if ($('#searcher').val() === '') {
            return;
        }
        $(this).addClass('show');
    },
    'onAfter': function() {
        if ($('#searcher').val() === '') {
            return;
        }
        if ($('.show:first').length > 0){
            $('html,body').scrollTop($('.show:first').offset().top);
        }
    },
    'hide': function() {
        $(this).removeClass('show');
    },
    'prepareQuery': function(val) {
        return new RegExp(val, "i");
    },
    'testQuery': function(query, txt, _row) {
        return query.test(txt);
    }
});

$('#searcher').focus();

An example here: link

    
15.02.2018 / 16:25
0

As you did not specify, you should be using Javascript pure, so you can use search :

var div= document.getElementById("Id_do_div");
var existe = div.innerHTML.search("texto") >= 0;

Reference: link

You can also use indexOf , which allows you to search from a point, in which case you can search for multiple occurrences of the same text:

link

    
15.02.2018 / 16:31