1 回答
TA贡献1818条经验 获得超11个赞
使用下面的管道终于成功了。
解决方案是创建一个包含 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 {
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;
}
}
添加回答
举报