突出显示所有匹配的单词TypeScript

问题描述 投票:0回答:1

[目前,我正在尝试在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
1个回答
0
投票

我知道了。所以我只需要更改这段代码:

return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(search, 'gi'),
  '<span style="background-color: yellow">' + `${search}` + '</span>') : text);

}

为此:

return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(`(${search})`, 'gi'),
  '<span style="background-color: yellow">' + `$1` + '</span>') : text);
© www.soinside.com 2019 - 2024. All rights reserved.