首页 > 解决方案 > jQuery:删除标签但保留内容?

问题描述

我知道以前有人问过这个问题,但我的问题略有不同。

我有一个看起来像这样的 html:

[caption id="attachment_12543" align="aligncentre" width="583"]<img class="wp-image-12543 size-full" src="https://tpc.googlesyndication.com/simgad/11307931562035142140" alt="" width="583" height="400">[/caption]

我需要删除caption标签并保留其内容(图像和文本)。

我试过这段代码,但它什么也没做。

$("caption").replaceWith(function() { return this.innerHTML; });

$("caption").replaceWith(function() { return this.innerHTML; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

[caption id="attachment_12543" align="aligncentre" width="583"]<img class="wp-image-12543 size-full" src="https://tpc.googlesyndication.com/simgad/11307931562035142140" alt="" width="583" height="400">[/caption]

有人可以就这个问题提出建议吗?

提前致谢。

标签: jquery

解决方案


此版本使用正则表达式仅删除开始和结束标题标签

$('div').html(function(){
  var html = this.innerHTML;
  
  html = html.replace(/(\[caption [^\]]+\])/, '');
  html = html.replace(/(\[\/caption\])/, '');

  return html;
});
img {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Other stuff
[caption id="attachment_12543" align="aligncentre" width="583"]
<img class="wp-image-12543 size-full" src="https://tpc.googlesyndication.com/simgad/11307931562035142140" alt="" width="583" height="400">
I got some text yo!!!
[/caption]
Even more stuff
</div>


推荐阅读