2 回答
![?](http://img1.sycdn.imooc.com/533e52b90001456f02000200-100-100.jpg)
TA贡献1806条经验 获得超8个赞
这是一种更简单的方法来使用 RegExp
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'highlight'
})
export class HighlightPipe implements PipeTransform {
transform(value: string, args: string[] | string): string {
if (!args.length) { return value; }
const pattern = Array.isArray(args) ? args.filter(arg => !!arg).join('|') : args;
const regex = new RegExp(pattern.concat('|<[^>]*>'), 'gi');
return value.replace(regex, (match) => /<[^>]*>/g.test(match) ? match: `<mark>${match}</mark>`);
}
}
我已经制作了管道,以便您可以根据需要使用两个数组或单个字符串突出显示。<[^>]*>是用于匹配 HTML 标签的 RegEx。
如果您想以区分大小写的方式进行搜索,只需i在创建RegExp以下内容时删除
const regex = new RegExp(pattern.concat('|<[^>]*>'), 'g');
然后在您的模板中,使用如下管道
<span [innerHTML]="sentence | highlight: highlightWords"></span>
哪里sentence和highlightWords在哪里
sentence: string = 'Hello, welcome to my beautiful world';
highlightWords: string[] = ['world', 'my'];
更新:我注意到使用元字符时管道不起作用。为了解决这个问题,可以使用正则表达式来逃避元字符如图所示这里。
const pattern = Array.isArray(args) ? args.filter(arg => !!arg).map(this.escapeRegex).join('|') : this.escapeRegex(args);
其中函数escapeRegex定义为
escapeRegex(word: string) {
return word.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
这是StackBlitz上的一个工作示例。
添加回答
举报