首页 > 解决方案 > Angular 在字符串中查找标记并用真实的 html 标记替换

问题描述

我从后端得到一个字符串,当我显示它时,它< br/>看起来像文本。

我想将它们转换为真正的 HTML 标记或用真正的断线替换它。

这是从后端检索到的字符串:

Description from backend Description from <br/> backend Description
from backend Description from backend <br/>Description <br/>from <br/>
backend Description from backend <br/> Description from backend
Description from backend Description from backend

这是我的功能:

ngOnInit(): void {
    this.uns = this.sentence$.subscribe(res => {
        this.sentence = res;
        if (this.sentence && this.sentence.length > 0) {
            this.sentence = res.replace('<br/>', '\n');
        }
    });
}

标签: javascriptangularreplacetags

解决方案


HTML不会仅仅因为你有它们而打印你的空白字符,它只会打印第一个空格然后跳过其余的。

您可以使用<pre></pre>标签来解决这个问题,然后您可以使用类似的东西sentence = sentence.split("<br>").join("\n")来解决这个<br/>问题。


推荐阅读