import { PipeTransform, Pipe } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Pipe({ name: 'highlight' }) export class HighlightPipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) { } transform(text: string, search, tagType = 'emphasis'): SafeHtml { if (search && text) { let pattern = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); pattern = pattern.split(' ').filter((t) => { return t.length > 0; }).join('|'); const regex = new RegExp(pattern, 'gi'); // Default to emphasized tag '', otherwise use the tag type specified // This uses the W3 convention for describing phrase tags (https://www.w3.org/TR/html401/struct/text.html) const tag = tagType === 'stronger' ? 'strong' : 'em'; return this.sanitizer.bypassSecurityTrustHtml( text.replace(regex, (match) => `<${tag}>${match}`) ); } else { return text; } } }