jQuery search and highlight text

highlight text

Using jQuery you can search and highlight text within a div from array of elements and wrap a highlight span around each word.

Example to search and highlight text:

<script type="text/javascript">
var regex = /(Rubbish|Like|Rough|Raw|Doggie|Billy)/ig;
$('#divID').each(function() {
var $this = $(this);
var text = $this.text();
if (regex.test(text)) {
$this.html(
$this.html().replace(regex, '<span>$1</span>')
);
}
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *