SO - 21401037

by Arun P Johny

HTML

<input class="search" />
<table class="projects-list">
    <tbody>
        <tr>
            <td>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</td>
            <td>Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.</td>
        </tr>
        <tr>
            <td>Aliquam rhoncus eros at augue. Suspendisse vitae mauris.</td>
            <td>I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:</td>
        </tr>
    </tbody>
</table>

CSS

.highlighted {
    background-color:yellow;
}

JavaScript

if (!RegExp.escape) {
    RegExp.escape = function (s) {
        return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
    };
}

$('input.search').keyup(function () {
    $(".projects-list > tbody > tr > td .highlighted").contents().unwrap();
    var search = RegExp.escape(this.value);
    $(".projects-list > tbody > tr > td").html(function (i, text) {
        return text.replace(new RegExp('(' + search + ')', 'gi'), '<span class="highlighted">$1</span>')
    })
})