在不允许 HTML 标签的情况下将 Markdown 转换为 HTML

我正在尝试构建一个textarea支持降价的。我已经成功地将降价转换为 HTML 以呈现预览,使用以下管道:


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

import * as marked from 'marked';

import * as DOMPurify from 'dompurify';


@Pipe({ name: 'markdown' })

export class MarkdownPipe implements PipeTransform {


  markdownToSafeHtml(value: string): string {

    const html = marked(value);

    const safeHtml = DOMPurify.sanitize(html);

    return safeHtml;

  }


  transform(str: string): string {

    if (str && str.length > 0) {

      const html = this.markdownToSafeHtml(str);

      return html.toString();

    }


    return str;

  }

}

以及以下 HTML:


<div [innerHTML]="value | markdown">

它正在工作并显示降价设计,但问题是我可以在降价字符串中添加任何 HTML 标签,并且因为我正在使用innerHTMLdiv 将使用它们,例如<h1>hello</h1>在此标签的预览中使用礼物,它应该将其呈现为文本。

  1. 没有其余的 HTML 标签,我如何转换为降价?

  2. 我已经尝试对 HTML 字母进行编码(例如&amp;等等),问题是在使用代码降价时,这个转换:<div>example</div>&lt;div&gt;example&lt;/div&gt;


POPMUISE
浏览 198回答 1
1回答

慕尼黑8549860

使用下面的管道终于成功了。解决方案是创建一个包含 HTML 的元素,并<code>使用该unescapeCodes函数反转元素中的 HTML 转义。import { Pipe, PipeTransform } from '@angular/core';import * as marked from 'marked';import * as DOMPurify from 'dompurify';@Pipe({ name: 'markdown' })export class MarkdownPipe implements PipeTransform {&nbsp; constructor() {&nbsp; }&nbsp; private escapeHTML(str: string) {&nbsp; &nbsp; return str.replace(/&/g, "&amp;")&nbsp; &nbsp; &nbsp; .replace(/</g, "&lt;")&nbsp; &nbsp; &nbsp; .replace(/>/g, "&gt;")&nbsp; &nbsp; &nbsp; .replace(/"/g, "&quot;")&nbsp; &nbsp; &nbsp; .replace(/'/g, "&#039;");&nbsp; }&nbsp; private unescapeHTML(str: string) {&nbsp; &nbsp; return str.replace(/&amp;/g, "&")&nbsp; &nbsp; &nbsp; .replace(/&lt;/g, "<")&nbsp; &nbsp; &nbsp; .replace(/&gt;/g, ">")&nbsp; &nbsp; &nbsp; .replace(/&quot;/g, "\"")&nbsp; &nbsp; &nbsp; .replace(/&#039;/g, "'");&nbsp; }&nbsp; private markdownToSafeHtml(value: string): string {&nbsp; &nbsp; const html = marked(value);&nbsp; &nbsp; return DOMPurify.sanitize(html);&nbsp; }&nbsp; private unescapeCodes(value: string) {&nbsp; &nbsp; const el = document.createElement("div");&nbsp; &nbsp; el.innerHTML = value;&nbsp; &nbsp; const codes = el.getElementsByTagName('code');&nbsp; &nbsp; for (let i = 0; i < codes.length; i++) {&nbsp; &nbsp; &nbsp; codes.item(i).innerText = this.unescapeHTML(codes.item(i).innerText);&nbsp; &nbsp; }&nbsp; &nbsp; return el.innerHTML.toString();&nbsp; }&nbsp; transform(str: string): string {&nbsp; &nbsp; if (!str || str.length == 0) return str;&nbsp; &nbsp; str = this.escapeHTML(str);&nbsp; &nbsp; let html = this.markdownToSafeHtml(str);&nbsp; &nbsp; html = this.unescapeCodes(html);&nbsp; &nbsp; return html;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript