import { PipeTransform, Pipe, ElementRef } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Pipe({ name: 'highlight' }) export class HighlightPipe implements PipeTransform { constructor(public sanitizer: DomSanitizer, private el: ElementRef) { } transform(text: string, keyword, field = '', findField = ''): SafeHtml { let needSearch = true; if (field && findField) { if (findField.indexOf(',') === -1) { needSearch = field === findField; } else { needSearch = findField.split(',').some(n => n === field); } } if (!needSearch) { return text; } if (keyword && text) { let pattern = keyword.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); pattern = pattern.split(' ').filter((t) => { return t.length > 0; }).join('|'); const regex = new RegExp(pattern, 'gi'); return this.sanitizer.bypassSecurityTrustHtml( // text.replace(regex, (match) => `${match}`) this.replaceContent(text, regex, (match) => `${match}`) ); } else { return text; } } parseHTML(html, context) { const t = (context || document).createElement('template'); t.innerHTML = html; return t.content.cloneNode(true); } private replaceContent(strMatch1, regex, match) { const matchReg1 = />.*?\<之间的内容 const strs = strMatch1.match(matchReg1); // 拿到所有符合的键值 if (strs && strs.length) { for (const aa of strs) { const rep_old = strs[aa]; // 拿到原始符合字符串 const rep_new = strs[aa].replace(regex, match); // 替换成目的字符串 const re2 = new RegExp(rep_old, 'g'); // 利用原始字符串生成正则 strMatch1 = strMatch1.replace(re2, rep_new); // 将符合的原始字符串替换成新字符串 } return strMatch1; } else { return strMatch1.replace(regex, match); } } }