jQuery:删除标签但保留内容?

时间:2018-05-09 18:08:58

标签: 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]

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

提前致谢。

1 个答案:

答案 0 :(得分:2)

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

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

  return html;
});
&#13;
img {
  border: 1px solid black;
}
&#13;
<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>
&#13;
&#13;
&#13;

相关问题