簡體   English   中英

離子 - 在 html 字符串中搜索文本並突出顯示?

[英]Ionic - Search text and highlight within html string?

嗨,我正在使用 ionic 加載本地 HTML 字符串的文章。

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

url 是本地 html 字符串。 現在我想要做的是添加搜索欄並在 html 字符串中搜索並突出顯示並滾動到該文本。

知道我該如何開始。 我添加了搜索欄

您可以使用 pipe 來應用您搜索的文本,它會是這樣的

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 | 突出顯示:'單詞'}}。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM