-1

我正在处理一个我无法弄清楚的奇怪的格式错误。在其他人的帮助下,我有一个小函数,它用指向实际 Twitter 用户的链接替换字符串中的所有 @[user]。它工作得很好,但是一旦我将它添加到我的网页中,它就开始有点吓人了。

这是字符串的示例。

If you want these foams Ima give you the chrome <a href="https://twitter.com/WillThaRapper" target="_blank">@WillThaRapper</a>

但是,一旦我将它附加到<p>要在页面上显示的元素,它看起来像这样。

If you want these foams Ima give you the chrome &lt;a href&#x3D;&quot;https:&#x2F;&#x2F;twitter.com&#x2F;WillThaRapper&quot; target&#x3D;&quot;_blank&quot;&gt;@WillThaRapper&lt;&#x2F;a&gt;

我很难弄清楚这一点。

4

1 回答 1

0

问题似乎是您正在向 HTML 添加一串 HTML 实体。要添加实际的 HTML,您可以使用 aDOMParser将实体转换为可以在 DOM 上呈现的 HTML:

const decodeEntities = str => {
  const doc = new DOMParser().parseFromString(str, "text/html");
  return doc.documentElement.textContent;
}

// input = the text you want to append to the page
const input = "If you want these foams Ima give you the chrome &lt;a href&#x3D;&quot;https:&#x2F;&#x2F;twitter.com&#x2F;WillThaRapper&quot; target&#x3D;&quot;_blank&quot;&gt;@WillThaRapper&lt;&#x2F;a&gt";

document.getElementById("output").innerHTML += decodeEntities(input);
<p id="output"></p>

于 2019-01-20T04:53:34.027 回答