Search code examples
javascriptjquerysearchfilterhighlight

jQuery filter and Highlight table


I have some problem with my code. On search i'm trying to find letter or a word and highlight it but have some problem for example when I search on word 'Aram' it return me 'ArAm'. When in a word I have more same letter and first one is capital all other letters replaced with capital letters. Can You please check my code and say what i do wrong.

example 'Aram' -> 'ArAm(<mark>A</mark>r<mark>A</mark>m)' but shuld be 'Aram(<mark>A</mark>r<mark>a</mark>m)'

JavaScript:

$("input").on("keyup", function () {
    var valThis = this.value;


    $('table').find('tr td').each(function () {
        if($(this).attr('data-search') !== 'false') {
            console.log('');


            var text = $(this).text();
            var textL = text.toLowerCase();
            var position = textL.indexOf(valThis.toLowerCase());

            if (position !== -1) {
                var matches = text.substring(position, ( valThis.length + position ));

                var regex = new RegExp(matches, 'ig');

                var highlighted = text.replace(regex, `<mark>${matches}</mark>`);

                console.log(highlighted);

                $(this).html(highlighted);

                setTimeout(function () {
                    if($(this).parent().find('mark').is(':empty')) {
                        $('mark').remove();
                    }
                }.bind(this),0);
            } else {
                console.log('sadasdasd');
                $(this).text(text);
            }
        }

        if($(this).parent().find('mark').length > 0) {
            $(this).parent().show();
        }else {
            $(this).parent().hide();
        }
    });
});

Here is my jsFiddle

Thanks for your help


Solution

  • Try this:

    var regex = new RegExp(valThis, 'ig');
    text = text.replace(regex, (match, $1) => {
      // Return the replacement
      return '<mark>' + match + '</mark>';
    });
    
    $(this).html(text);
    

    JSFiddle