rtn
rtn

Reputation: 2034

Regex helped needed for angular filter which highlights matching text from html

I have this which works but but the regex is matching with html tags, is there any way I could get it to ignore html tags. Could anyone help me to modify the regex expression so my class is only applied to text and not matching html tags?

angular.module('my.filters')
    .filter('highlight', function ($sce) {
        return function (text, filterPhrase) {
            if (filterPhrase) text = text.replace(new RegExp('(' + filterPhrase + ')', 'gi'), '<span class="quick-find-highlight">$1</span>');
            return $sce.trustAsHtml(text);
        };
    });

Upvotes: 0

Views: 777

Answers (1)

jcubic
jcubic

Reputation: 66470

You can try following code, where I split by tags and replace only when string is not a tag.

angular.module('my.filters')
    .filter('highlight', function($sce) {
        return function(text, filterPhrase) {
            if (filterPhrase) {
                var tag_re = /(<\/?[^>]+>)/g;
                var filter_re = new RegExp('(' + filterPhrase + ')', 'gi');
                text = text.split(tag_re).map(function(string) {
                    if (string.match(tag_re)) {
                        return string;
                    } else {
                        return string.replace(filter_re, 
                                              '<span class="quick-find-highlight">$1</span>');
                    }
                }).join('');
            }
            return $sce.trustAsHtml(text);
        };
    });

Upvotes: 1

Related Questions