简体   繁体   English

突出显示 html 原始文本中的特定文本

[英]Highlighting a specific text which in html raw text

What I'm trying to accomplish is highlight a text that given by parameter inside a raw text which format is HTML.我想要完成的是突出显示由格式为 HTML 的原始文本中的参数给出的文本。

I'm working with Angular 7 and tried to do that jQuery functions and some third party libs but did not do that yet.我正在使用 Angular 7 并尝试使用 jQuery 函数和一些第三方库,但还没有这样做。

Here the scenario;这里的场景;

raw HTML text comes as below原始 HTML 文本如下

<div #rawContentContext class="form-group m-form__group row col-lg-12" style="width:100%; height: 100vh; overflow:scroll;">
  {{ getHtmlRawContent() }} 
</div>

getHtmlRawContent() method returns HTML raw code as string getHtmlRawContent()方法将 HTML 原始代码作为字符串返回

I've tried to handle this issue with markjs and hilitorjs but it didn't work because they're trying to solve this by replacing keyword with <mark> keyword so the text already raw HTML so those steps were not work.我试图用 markjs 和 hilitorjs 处理这个问题,但它没有用,因为他们试图通过用<mark>关键字替换关键字来解决这个问题,所以文本已经是原始 HTML,所以这些步骤不起作用。

Here approach and code example;这里的方法和代码示例;

<script type="text/javascript">
   var myHilitor = new Hilitor(document.getElementById("rawContentContext"));
   myHilitor.apply("exceeded");
</script>

It actually works some scenarios which rendering HTML code rather than outputting as raw.它实际上适用于一些渲染 HTML 代码而不是输出为原始代码的场景。

Also tried with pipe也试过用管道

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

@Pipe({
    name: 'highlight'
})

export class HighlightSearch implements PipeTransform {

    transform(value: any, args: any): any {
        if (!args) {return value;}
        if (value!=null){
            var re = new RegExp(args, 'gi');
            return value.replace(re, '<p style="background-color: red;"> <mark>$&></mark> </p>');
        }

    }
}

And HTML side和 HTML 端

{{ getHtmlRawContent() | highlight:getSearchedKeyWord() }}

Thank you.谢谢你。

You're almost there, but in Angular, code between double braces {{<code>}} will be rendered as escaped html text (plain text).你快到了,但在 Angular 中,双大括号{{<code>}}之间的{{<code>}}将呈现为转义的 html 文本(纯文本)。 In order to your string be rendered as html, it must be in the attribute innerHTML of your parent element, like this:为了将您的字符串呈现为 html,它必须位于您的父元素的属性innerHTML中,如下所示:

<div #rawContentContext class="form-group m-form__group row col-lg-12"
    style="width:100%; height: 100vh; overflow:scroll;"
    [innerHTML]="getHtmlRawContent() | highlight:getSearchedKeyWord()">
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM