Highlight the search text - angular 2

前端 未结 7 811
心在旅途
心在旅途 2020-12-01 05:22

A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result. These are the h

相关标签:
7条回答
  • 2020-12-01 06:05

    I would suggest to escape the search String like this

     RegExp.escape = function(string) {
      if(string !== null){ return string.toString().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
      } else return null
    };
    
    @Pipe({
        name: 'highlight'
    })
    export class HighlightPipe implements PipeTransform {
      constructor(private sanitizer: DomSanitizer){ }
    
      transform(value: any, args: any): any {
        if (!args || value == null) {
          return value;
        }
        // Match in a case insensitive maneer
        const re = new RegExp(RegExp.escape(args), 'gi');
    
          const  match = value.match(re);
    
    
    
        // If there's no match, just return the original value.
        if (!match) {
          return value;
        }
    
        const replacedValue = value.replace(re, "<mark>" + match[0] + "</mark>")
        return this.sanitizer.bypassSecurityTrustHtml(replacedValue)
      }
    }
    
    0 讨论(0)
提交回复
热议问题