如果已知所有可能的自定义标记,则可以在将字符串传递给
[innerHTML]
结合。方法
encodeCustomTags
在以下代码段中,使用正则表达式替换
<customTag>
具有
<customTag>
:
private customTags = [
"CUSTOM_TAG",
"otherTag",
];
myHtml = this.encodeCustomTags("the <CUSTOM_TAG>boy</CUSTOM_TAG> went to the <b>store</b>");
private encodeCustomTags(html: string): string {
let regex: RegExp;
for (let tag of this.customTags) {
regex = new RegExp(`<(/?)${tag}>`, "gi");
html = html.replace(regex, `<$1${tag}>`)
}
return html;
}
见
this stackblitz
一个演示。