Search code examples
javascriptjqueryregexmustache

Highlight matched text with case sensitive for auto suggestion


I am working for auto suggestion, where i need to match the key term and if the key term matched make it highlighted. I am done with this but the problem is while matching I am looking with ignore case. so In result if i am looking for home and result is Home its become home while displaying on fronend. I am using mustache as a templating engine for Ui. Used code is:

var highLightRegExp = new RegExp(r.q , "ig");
//r.q - is query term.
            // Highlight the query part of the search term
            highlightText : function () {
              return function (text, render) {
                var renderTxt = render(text),
                    decodedText = $("<div/>").html(renderTxt).text();
                return decodedText.replace(highLightRegExp , "<b class='colorFFF'>" + r.q + "</b>");
              };
            }

How to match all the characters but while displaying it should be in original case.


Solution

  • Use $& (which is the matched substring) in the replacement instead of the original string.

    For example:

    decodedText.replace(highLightRegExp , "<b class='colorFFF'>$&</b>");
    

    Also don't forget to escape the string before using it as an expression, or you could get some issues when user uses regex meta characters ([home]*).