Search and highlight text in HTML

by Bianca Kuehweidner

HTML

<div id="test">
  this is <a href="#">my</a> text that needs highlighting my text<br />
  <table>
  <tr>
    <td>Lorem ipsum</td>
    <td>dolor sit</td>
  </tr>
  </table>
</div>

CSS

table td { border: solid 1px #333; }

JavaScript

var src_str = $("#test").html();
var term = "ipsum";
term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("("+term+")", "gi");

src_str = src_str.replace(pattern, "<mark>$1</mark>");
src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark>$4");

$("#test").html(src_str);