js treats the String string as HTML and displays it on the page

A message of type string is received and needs to be converted to html and displayed on the page.

The implementation is as follows:

Examples of received parameters:

  const data = {
      html: "<h1 style=\"text-align: center;\">213</h1><p><span style=\"color: rgb(207, 19, 34);\">jintian</span></p><p><strong>你好吗</strong></p><p><br></p><p><br></p><p><strong>lfhajd</strong><span style=\"color: rgb(206, 145, 120);\">article.text.disclaimer.tips1</span><span style=\"color: rgb(51, 51, 51); background-color: rgb(255, 255, 255); font-size: 14px;\">使用innerHTML属性将字符串转换为HTML对象 在这里,我们将有一个函数stringToHTML,它将原始字符串作为其参数。之后,我们将创建一个div,并希望传递其中给出的字符串。 我们也可以将它传递给 HTML 正文,但为了整洁,我们需要一个div元素。 接下来,新创建的div将与一个实例相关联dom(假设)。因此,对于dom,我们将设置innerHTML属性,然后传递字符串。 将return是我们创建dom的函数的实例。</span></p><p><strong>本文来自The Block,原文作者:RT Watson & Lucy Harley-McKeo发行方 Circle 发布2022年12月的储备报告,目前44,553,543,212 USDC 由托管账户中的44,693,963,701美元支持,其中很大一部分为美国国债。Circle 的储备基金注册为政府货币市场基金,该基金的股权由 Circle 全资拥有,包括14种不同的美国债券,价值超过235亿美元,该基金还持有4890万美元现金。\n此外,还有3300万美元应归该基金(due to the Fund),但被“时间和结算差异”所抵消。持有 Circle 现金储备的美国银行包括纽约梅隆银行、Citizens Trust Bank、Customers Bank、New York Community Bank、Signature Bank、硅谷银行和 Silvergate Bank。(Cointelgraph) 译者|本文Luc译者|本文来自The Block,原文作者:RT Watson & Lucy Harley-McKeow译者|本文来自The Block,原文作者:RT Watson &译者|</strong></p><h1 style=\"text-align: center;\">210000003</h1><p><span style=\"color: rgb(207, 19, 34);\">jintian</span></p><p><strong>你好吗</strong></p><p><br></p><p><span style=\"color: rgb(54, 88, 226);\">hhh</span></p><p>asd</p><p><br></p><p><img src=\"https://这是图片地址icon/20230131/2023013116443929716751546792967983598873.jpeg\" alt=\"\" data-href=\"\" style=\"\"/></p>",

  }

code:

  useEffect(() => {

    const res1 = data.html.replace(new RegExp("\"", "gm"), '"');
    const res = res1.replace(new RegExp("\n", "gm"), "<br />");
    const aa = res.replace(new RegExp("\r", "gm"), "<br />");
    const qq = aa.replace(new RegExp("<p><br></p>", "gm"), "<br />");
 
    const container = document.getElementById('articleContainer');
    container?.appendChild(createDocument(qq));

  }, []);

  const createDocument = (txt) => {
    const template = `<div class='child'>${txt}</div>`;
    let doc = new DOMParser().parseFromString(template, 'text/html');
    let div = doc.querySelector('.child');
    return div;
  }
   <div id="articleContainer">
        </div>

This is done.

Guess you like

Origin blog.csdn.net/chhpearl/article/details/128831568