如何将跨度环绕 HTML 的一部分?

How can I wrap a span around a section of HTML?

我正在尝试弄清楚如何从某些生成的 HTML.

中定位一段字符

我的输出是:

<div class="entry-content">
    [embed]https://www.youtube.com/watch?v=y545JdKuHOs[/embed] This is some other copy.
</div>

期望的输出是:

<div class="entry-content">
    <span class="hide">
      [embed]https://www.youtube.com/watch?v=y545JdKuHOs[/embed]
    </span> This is some other copy.
</div>

我的目标是将 [embed] 标签包装在 <span class="hide"></span> 中,我可以通过 CSS 定位。这个 HTML 有多个实例,在 [embed][/embed] 中有不同的链接,所以我很可能需要找到一种方法将整个代码包装成一个跨度。

我正在调查 .wrap(),但没有 avail.you。

要实现此目的,您可以使用带有正则表达式的 html() 方法,该正则表达式提取 [embed]*[/embed] 模式并将其包装在 <span> 中。试试这个:

$('.entry-content').html(function(i, html) {
  return html.replace(/(\[embed\].+\[\/embed\])/gi, '<span class="hide"></span>');
});
.hide { background-color: yellow; } /* just for demo purposes */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry-content">
    [embed]https://www.youtube.com/watch?v=y545JdKuHOs[/embed] This is some other copy.
</div>
<div class="entry-content">
    [embed]https://www.youtube.com/watch?v=dK45JuOsy5H[/embed] This is some other copy.
</div>