Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 72388

Text highlight based on input term behaves unexpectedly

$
0
0

This is how the html paragraph format looks like before the search term entered.

enter image description here

After entering the term it loses the initial format (returns plain text) and duplicates the p text by the number of consecutive characters found (actually I know why is that, but again no idea how to avoid it):

enter image description here

What I want is to keep my initial html format, with those higlighted words and of course to avoid text duplication.


Here is my code snippet:

function searchHighlight(searchText) {
  if (searchText) {
    var content = $("p").text();
    // i for case insensitive, g search all matches
    var searchExpression = new RegExp(searchText, "ig"); 
    var matches = content.match(searchExpression);
    if (matches) {
      $("p").html(content.replace(searchExpression, function(match) {
        return "<span class='highlight'>" + match + "</span>";
      }));
    } else {
      $(".highlight").removeClass("highlight");
    }
  } else {
    $(".highlight").removeClass("highlight");
  }
}

$("#search").keyup(function() {
  // Return the value inside the text box
  searchHighlight($(this).val()); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><p><span>jQuery selektori</span> omogućavaju selektovanje i upravljanje HTML elementima.
  Selektori traže HTML elemente na osnovu njihovih identi೰katora, klasa, atributa, 
  vrednosti atributa i dr. Bazirani su na CSS selektorima, ali postoje još neki. 
  Svi selektori u <span>jQuery-ju</span> počinju sa znakom dolara i zagradama: $() .
</p><p id="paragraph"><span>Selektor $("*")</span> selektuje sve elemente.<span>– Selektor $(this)</span> selektuje element na koji se odnosi funkcija koja ga obuhvata.<span>– Selektor $("p.intro")</span> selektuje sve p elemente sa atributom class="intro" . 
  Uvod u Veb i Internet Tehnologije 133<span>– Selektor $("p:first")</span> selektuje prvi p element.<span>– Selektor $("ul li:first")</span> selektuje prvi li element prvog ul elementa.<span>– Selektor $("ul li:first child")</span> selektuje prvi li element svakog ul elementa.<span>– Selektor $("[href]")</span> selektuje sve elemente koje imaju postavljen atribut 
  href . – Selektor $("a[target='_blank']") selektuje sve elemente a sa atributom target="_blank"
  . – Selektor $("a[target!='_blank']") selektuje sve elemente a koji
  nemaju atribut target="_blank" . – Selektor

</p>

Viewing all articles
Browse latest Browse all 72388

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>