【发布时间】:2020-05-28 19:39:46
【问题描述】:
目前,我正在尝试在我的 Angular 项目的文本中实现对搜索词的突出显示。我将搜索操作作为一个单独的组件,我想创建一个管道来突出显示文本中搜索到的单词的所有匹配项。
@Pipe({name: 'highlight'})
export class TextHighLightPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
transform(text: any, search: string): SafeHtml {
//takes care of any special characters
if (search !== undefined && search !== null) {
search = search.toString().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
text += '';
return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(search, 'gi'),
'<span style="background-color: yellow">' + `${search}` + '</span>') : text);
}
}
此代码工作正常,但它用搜索的单词替换所有匹配项,所以如果我有一个以大写开头的单词,当我用小写搜索它时,转换函数会将它替换为小写一,这是实际问题.. 例如:
要搜索的文本:This 只是 this 代码的示例文本
搜索词:这个
结果:this只是this代码的示例文本
【问题讨论】:
标签: string typescript search replace