突出显示语句中的多个字符串 - Javascript

我需要在 HTML 中的语句中突出显示多个单词。


Ex: words: ['Hello', 'world', 'my']  

Statement: 'Hello, welcome to my beautiful world'

我可以在正常情况下使用正则表达式查找和替换来完成它(比如用一些标记替换每个单词的出现,比如


<span  class="highlight-span"> word </span>.    

但问题是,如果任何像 spa、span、class、lass、high 这样的词是我的替换标记字符串的一部分,我就会遇到问题。)


关于以更好的方式做到这一点的任何想法?


下面是代码供您参考。


import {

    Pipe,

    PipeTransform

} from '@angular/core';

@Pipe({

    name: 'highlight'

})

export class HighlightSearch implements PipeTransform {

    transform(value: string, args: string): any {

        if (args && value) {

            let startIndex = value.toLowerCase().indexOf(args.toLowerCase());

            if (startIndex != -1) {

                let endLength = args.length;

                let matchingString = value.substr(startIndex, endLength);

                return value.replace(matchingString, "<span  class="highlight-span">" + matchingString + "</span>");

            }


        }

        return value;

    }

}

在这种情况下,我不能使用诸如 mar、mark 之类的搜索词。我怎样才能摆脱这些问题?


绝地无双
浏览 128回答 2
2回答

慕森卡

这是一种更简单的方法来使用 RegExpimport { Pipe, PipeTransform } from '@angular/core';@Pipe({&nbsp; &nbsp; name: 'highlight'})export class HighlightPipe implements PipeTransform {&nbsp; &nbsp; transform(value: string, args: string[] | string): string {&nbsp; &nbsp; &nbsp; &nbsp; if (!args.length) { return value; }&nbsp; &nbsp; &nbsp; &nbsp; const pattern = Array.isArray(args) ? args.filter(arg => !!arg).join('|') : args;&nbsp; &nbsp; &nbsp; &nbsp; const regex = new RegExp(pattern.concat('|<[^>]*>'), 'gi');&nbsp; &nbsp; &nbsp; &nbsp; return value.replace(regex, (match) => /<[^>]*>/g.test(match) ? match: `<mark>${match}</mark>`);&nbsp; &nbsp; }}我已经制作了管道,以便您可以根据需要使用两个数组或单个字符串突出显示。<[^>]*>是用于匹配 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) {&nbsp; &nbsp; return word.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');}这是StackBlitz上的一个工作示例。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript