Identify a span tag that is inside a string with jquery

2

Good morning. I have a function that highlights the text of a list, according to the word (s) by which the user searches. The problem is that when they write two words for example "Juan Carlos" I want the Juan and Carlos to change color in the list. In this case it is good. But if I search "Juan id", I want to highlight the id of the span that was previously inserted and the html code is broken. How can I identify if the word is part of the attributes of a label? or if it is contained between < & gt ;. Try to put in the text "CARLOS", "JUAN", "ID". And then try "CARLOS ID"

Thank you very much

function resaltar(control, txtResaltar) {
  var str = $("#resultado").text().trim();
  var textBusq = $("#textoBuscar").val();

  if (textBusq == null || textBusq == "")
    if (txtResaltar != null && txtResaltar != "")
      textBusq = txtResaltar;
    else {
      return str;
    }

  var element = textBusq.split(' ');
   
  $.each(element, function(index, contenido) {
    var regEx = new RegExp(contenido, "gi");
    str = str.replace(regEx, function(a, b) {
      return '<span id="span2" style="font-weight:bold;color:red">' + a + '</span>';
    });
  });

  $("#resultado").html(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<input type="text" id="textoBuscar">
<input type="button" onclick="resaltar()" value="Buscar" />

<span id="resultado">JUAN CARLOS ID</span>
    
asked by Ariel Octavio D'Alfeo 12.01.2016 в 20:15
source

1 answer

5

Change the highlight function a bit, the idea now is that I evaluated all the possible searches in the same regular expression so that I did not evaluate the HTML that you add in the other iterations

function resaltar(control, txtResaltar) {
    var str = $("#resultado").text().trim();
    var textBusq = $("#textoBuscar").val();

    if (textBusq == null || textBusq == "")
        if (txtResaltar != null && txtResaltar != "")
            textBusq = txtResaltar;
    else {
        return str;
	}

    var element = textBusq.split(' ');
    var regexfilter="";
    $.each(element, function(index, contenido) {
         regexfilter+=contenido+"|";
    });
   var regEx = new RegExp(regexfilter, "gi");
   str = str.replace(regEx, function(a, b) {
       return '<span id="span2" style="font-weight:bold;color:red">' + a + '</span>';
    });
    $("#resultado").html(str);	  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<input type="text" id="textoBuscar">
<input type="button" onclick="resaltar()" value="Buscar" />

<span id="resultado">JUAN CARLOS ID</span>
    
answered by 12.01.2016 / 20:51
source