Search code examples
javascriptangularjsangular-filters

angular js highlighter filter highlight text and change text also


enter image description here

my highlight filter

app.filter('highlightWord', function () {
return function (isSectionData, selectedWord) {
    if (!isSectionData) return '';
    // var items = selectedWord.split(" ");
    var items = selectedWord.trim().replace(/ OR /g, ' ').replace(/ AND /g, ' ').replace(/ - /g, '').replace(/-/g, '').replace(/"/g, '').split(' ');
    for (var i = 0, len = items.length; i < len; i++) {
        var pattern = new RegExp(items[i], "gi");
        if (isSectionData && items[i] != "") {
            isSectionData = isSectionData.replace(pattern, '<span class="highlighted">' + items[i] + '</span>');
        }
    }
    return isSectionData;
};});

in this highlighter is working fine but in some case, it changes my HTML paragraph

like I search for 'MI' word in highlight search world like 'similar' and highlight and change this to 'siMIlar'

Is there any something I need to change for correct my result


Solution

  • Some changes on code

    app.filter('highlightWord', function () {
        return function (isSectionData, selectedWord) {
            if (!isSectionData) return '';
            // var items = selectedWord.split(" ");
            var items = selectedWord.trim().replace(/ OR /g, ' ').replace(/ AND /g, ' ').replace(/ - /g, '').replace(/-/g, '').replace(/"/g, '').split(' ');
            for (var i = 0, len = items.length; i < len; i++) {
                var pattern = new RegExp(' (' + items[i] + ')', "ig");
                if (isSectionData && items[i] != "") {
                    isSectionData = isSectionData.replace(pattern, function (match) {
                        return ' <span class="highlighted">' + match + '</span> ';
                    });
                }
            }
            return isSectionData;
        };
    });
    

    changes are pattern search text with space in RegExp with ig reg expression