Search string on page with Javascript

Asked

Viewed 2,107 times

0

How can I perform a search in a DIV resembling Chrome’s Ctrl+F with javascript?

Case-independent, lowercase, accents, etc.

So far I have the result below. I take the term found and check if there is occurrence in the text. But when the occurrence has accent, does not highlight (does not find).

I am using this script to have 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);

}

https://pastebin.com/8U5SXQBV

inserir a descrição da imagem aqui

  • Specify your question... What have you managed to do? The search will be done through a input? Post your code.

  • I’ll edit the question to explain it better

  • I tested your code and it’s even picking up the accents. See if this is it: https://jsfiddle.net/x28g6qn2/

  • The opposite does not work. For example, let’s take the example of the above img, if the name in the text was "CLAUDIA", it would not find.

  • Yes, you would. See: https://jsfiddle.net/x28g6qn2/4/

  • So far I do not understand. Your code is finding everything I test. Maybe you meant that if you typed "Claudia", for example, you would find "Cláudia", "CLAUDIA", "CLÁUDIA", "Claudia" etc... that would be it?

  • @dvd, https://jsfiddle.net/x28g6qn2/9/

  • What is the relationship of the question with Vue.js?

  • Nothing. It doesn’t even matter.

  • So that’s what I said. You want to find the word regardless of accents or caps. Only the question says otherwise: "Taking uppercase, lowercase, accents, etc."

Show 5 more comments

4 answers

1


I added in the code a function that removes all accents and converts both the text of the div the term searched. This makes it easier to locate the term searched in the text.

Then after the match in the text raw (accent-free and lowercase) reset regex to find and replace occurrences in the original text with the search term.

See 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>
<div id="texto">
   Acentos são permitidos e até LETRAS MAIÚSCULAS coração e CLÁUDIA coração
</div>

1

Another alternative way I found without using regex was to use while and for. The while takes the positions of the term within the text raw and then the for replaces the original text:

See 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>
<div id="texto">
   Acentos são permitidos e até LETRAS MAIÚSCULAS coracao e CLÁUDIA coração coração
</div>

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: http://jsfiddle.net/ZLhAd/369/

  • When there is an accent record, such as "dé[email protected]", you will not find it. But it helped me to improve my logic a little.

0

  • Sorry! I’m using Vuejs. The search resembles paralavras with accents.

  • I am using this script to have the result in the image. https://pastebin.com/8U5SXQBV var searchTerm = variavelEncontrada;&#xA; var html = texto;&#xA; &#xA; var pattern = "([^\\w]*)(" + searchTerm + ")([^\\w]*)";&#xA; var rg = new RegExp(pattern, "gi");&#xA; var match = rg.exec(html);&#xA; if(match) {&#xA; html = html.replace(rg,match[1] + "<b>"+ match[2] +"</b>" + match[3]);&#xA; }

  • Put it in the question to be clear

  • Note that in line 8 I add a highlight (<b>) in the occurrence found

  • @Josivansousa, edit your question and put the code you are using there, it is easier for everyone to see and give suggestions

Browser other questions tagged

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