Search a text and highlight

Search a text and highlight

I am trying to Search a text and highlight it inside an HTML element. But it is not working properly. Just first character of searched text is highlighted.

  1. $ ( ".modal_search" ). on ( "keyup" , function () {
    var Id = $ ( this ). attr ( 'id' );
    var searchItem = $ ( this ). val ();

    $ ( '#textModal_' + Id ). find ( ".highlight" ). removeClass ( "highlight" );

    var searchText = $ ( '#textModal_' + Id ). html ();

    var reg = new RegExp ( searchItem , 'gi' );

    var txt = searchText . replace ( reg , function ( str ) {
    return "<span class='highlight'>" + str + "</span>"
    });

    if ( searchItem != "" ) {
    $ ( '#textModal_' + Id ). html ( txt );
    }
    });

This code is also not keeping the formatting of content.