我需要在搜索段落中突出显示关键字。
因此,我创建了一个将关键字包装到一个范围中并添加类.highlight
的管道。
问题是:我的段落包含链接和特殊字符,
例如:"href=\"keyword.co.uk/\"
。
因此,如果管道找到了我在href
元素内搜索的关键字,它也将替换它。
请,建议如何避免替换链接和特殊字符?
let data = [{
"question": "Lorem ipsum dolor sit amet",
"answer": ["Lorem ipsum <a href=\"https://www.keyword.co.uk/\" data-rt-link-type=\"external\" target=\"_blank\">dolor</a> sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."]
}]
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
@Pipe({name: 'highlightKeyword'})
export class HighlightKeyword implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(text: string, search): SafeHtml {
if (search && text) {
let pattern = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
console.log(pattern)
pattern = pattern.split(' ').filter((t) => {
return t.length > 0;
}).join('|');
const regex = new RegExp(pattern, 'gi'); console.log(text)
return this.trustHtml(
text.replace(regex, (match) => `<span class="highlight">${match}</span>`)
);
} else {
return this.trustHtml(text);
}
}
trustHtml(htmlSnip: any) {
return this.sanitizer.bypassSecurityTrustHtml(htmlSnip);
}
}
<input [formControl]="searchQuery" [placeholder]="placeholderText">
<div *ngFor="let article of Articles">
<mat-card>
<mat-card-title [innerHTML]="data.question | highlightKeyword: searchQuery">
</mat-card-title>
<mat-card-content>
<p *ngFor="let paragraph of data.answer"
[innerHTML]="paragraph | highlightKeyword: searchQuery">
</p>
</mat-card-content>
</mat-card>
</div>