【问题标题】:How can we append html within html string using javascript/typescript?我们如何使用 javascript/typescript 在 html 字符串中附加 html?
【发布时间】:2021-03-23 05:53:41
【问题描述】:

我有一个这样的 HTML 字符串:

    "Some text <span>something</span> some more text <span>something inside second span</span>...<span>nth span</span>"

我想创建一个函数,在每个 span 标签关闭之前,在每个 span 中注入一些 HTML。让我们取anchor标签,让最终的HTML字符串变成这样:

    "Some text <span>something<a>anchor</a></span> some more text <span>something inside second span<a>anchor</a></span>...<span>nth span<a>anchor</a></span>"

请有人告诉我如何实现这一目标?请注意,注入的 dom 始终是相同的。

我试过了:

    content.replace("</span>","<a>anchor</a></span>");

但它只替换了该 html 内容字符串中的第一个结束 span 标签。

【问题讨论】:

  • 不能 100% 确定您要完成什么,但您可以使用 .ts 文件中的变量吗?
  • 最新JS提供content.replaceAll("&lt;/span&gt;","&lt;a&gt;anchor&lt;/a&gt;&lt;/span&gt;");
  • 你也可以对这个content.replace(/&lt;\/?[/]+span[^&gt;]*&gt;/g, " &lt;a&gt;anchor&lt;/a&gt;&lt;/span&gt; ")使用正则表达式。

标签: javascript html angular typescript


【解决方案1】:

你可以使用 replaceAll 方法来解决这个问题。

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 2019-11-28
    • 2016-11-14
    • 2014-05-29
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 2016-08-23
    • 2014-04-21
    相关资源
    最近更新 更多