【问题标题】:Highlighting all match words TypeScript突出显示所有匹配词 TypeScript
【发布时间】: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


    【解决方案1】:

    我想通了。所以我只需要更改这段代码:

    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);
    

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2019-05-18
      • 2012-08-04
      • 1970-01-01
      • 2014-04-24
      相关资源
      最近更新 更多