1 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
使用下面的管道終于成功了。
解決方案是創(chuàng)建一個(gè)包含 HTML 的元素,并<code>使用該unescapeCodes函數(shù)反轉(zhuǎn)元素中的 HTML 轉(zhuǎn)義。
import { Pipe, PipeTransform } from '@angular/core';
import * as marked from 'marked';
import * as DOMPurify from 'dompurify';
@Pipe({ name: 'markdown' })
export class MarkdownPipe implements PipeTransform {
constructor() {
}
private escapeHTML(str: string) {
return str.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
private unescapeHTML(str: string) {
return str.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "\"")
.replace(/'/g, "'");
}
private markdownToSafeHtml(value: string): string {
const html = marked(value);
return DOMPurify.sanitize(html);
}
private unescapeCodes(value: string) {
const el = document.createElement("div");
el.innerHTML = value;
const codes = el.getElementsByTagName('code');
for (let i = 0; i < codes.length; i++) {
codes.item(i).innerText = this.unescapeHTML(codes.item(i).innerText);
}
return el.innerHTML.toString();
}
transform(str: string): string {
if (!str || str.length == 0) return str;
str = this.escapeHTML(str);
let html = this.markdownToSafeHtml(str);
html = this.unescapeCodes(html);
return html;
}
}
添加回答
舉報(bào)