0

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);
        };
    });
2
  • Can you show your regular expression (filterPhrase)? Commented Mar 25, 2015 at 10:51
  • It will just be a text string which the user will type in, works sort of like Ctrl + f in the browser. Commented Mar 25, 2015 at 10:53

1 Answer 1

1

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);
        };
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.