Ionic-在html字符串中搜索文本并突出显示?

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

嗨,我正在使用ionic来加载作为本地HTML字符串的文章。

 <ion-content padding>
  <p  [innerHTML]="url"></p>
</ion-content>

url是本地html字符串。现在,我要执行的操作是添加搜索栏,并在该html字符串和higlight中搜索并滚动到该文本。

任何想法我该如何开始。我已经添加了搜索栏

html typescript ionic-framework
1个回答
0
投票

您可以使用管道将您搜索的文本应用于此文本,>]

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'highlight'})

export class HighlightPipe implements PipeTransform {
    transform(text: string, search): string {
        try {
            if (text && search ) {
                text = text.toString(); // sometimes comes in as number
                search = search.trim();
                if (search.length > 0) {
                    let pattern = search.trim().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
                    pattern = pattern.split(' ').filter((t) => {
                        return t.length > 0;
                    }).join('|');
                    let regex = new RegExp(pattern, 'gi');

                    text = text.replace(regex, (match) => `<span class="highlight">${match}</span>`);
                }
            }
        }
        catch (exception) {
            console.error('error in highlight:', exception);
        }
        return text;
    }
}

如果需要,您可以更改.scss:

.highlight {
background-color:#FFFF00;
}

因此,要在模板中使用,将类似于:{{myText |高亮显示:“单词”}}。

© www.soinside.com 2019 - 2024. All rights reserved.