Baqer Naqvi
Baqer Naqvi

Reputation: 6514

How to highlight searched string in the result?

i am fetching data using Like keyword, that mean results may contain not exactly match. Now i want to highlight the searched string form the whole data? I am showing data in a table. is there any easy way to do this?

Here is code to show data

<table class="table table-striped table-bordered bootstrap-datatable datatable">
  <thead>
      <tr>
          <th>Surah</th>
          <th>Ayah</th>
          <th>Contents</th>
      </tr>
 </thead>   
  <tbody>    
    @foreach (var n in @ViewBag.test)
    {
        <tr>
        <td class="center"> @n.surah_name </td>
        <td class="center">    @n.ayah  </td>
        <td style="text-align:right; font-size: 20px; height:90px; vertical-align:middle; line-height : 75px"> @n.verse   </td>
       </tr>
    }

         </tbody></table>

i want to highlight on click event of button!

Upvotes: 0

Views: 1643

Answers (1)

Zealot
Zealot

Reputation: 697

// escape by Colin Snover
// Note: if you don't care for (), you can remove it..
RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

function highlight(term, base) {
  if (!term) return;
  base = base || document.body;
  var re = new RegExp("(" + RegExp.escape(term) + ")", "gi"); //... just use term
  var replacement = "<span class='highlight'>" + term + "</span>";
  $("*", base).contents().each( function(i, el) {
    if (el.nodeType === 3) {
      var data = el.data;
      if (data = data.replace(re, replacement)) {
        var wrapper = $("<span>").html(data);
        $(el).before(wrapper.contents()).remove();
      }
    }
  });
}

function dehighlight(term, base) {
  var text = document.createTextNode(term);
  $('span.highlight', base).each(function () {
    this.parentNode.replaceChild(text.cloneNode(false), this);
  });
}

See it in action

From: https://stackoverflow.com/a/3241437/3272179

Upvotes: 2

Related Questions