Highlighting a filtered result in AngularJS

前端 未结 13 2112
醉话见心
醉话见心 2020-12-01 00:12

I\'m using a ng-repeat and filter in angularJS like the phones tutorial but I\'d like to highlight the search results in the page. With basic jQuery I would have simply pars

13条回答
  •  醉酒成梦
    2020-12-01 00:32

    About the problems with special caracter, I think just escaping you might lose regex search.

    What about this:

    function(text, search) {
        if (!search || (search && search.length < 3)) {
            return $sce.trustAsHtml(text);
        }
    
        regexp  = '';
    
        try {
            regexp = new RegExp(search, 'gi');
        } catch(e) {
            return $sce.trustAsHtml(text);
        }
    
        return $sce.trustAsHtml(text.replace(regexp, '$&'));
    };
    

    An invalid regexp could be user just typing the text:

    • valid: m
    • invalid: m[
    • invalid: m[ô
    • invalid: m[ôo
    • valid: m[ôo]
    • valid: m[ôo]n
    • valid: m[ôo]ni
    • valid: m[ôo]nic
    • valid: m[ôo]nica

    What do you think @Mik Cox?

提交回复
热议问题