通过JavaScript或jQuery删除P标记,其中包含不间断的空格

Remove P tag with non-breaking space inside of it via JavaScript or jQuery

本文关键字:包含 不间断 空格 标记 JavaScript jQuery 删除 通过      更新时间:2023-10-17

因此,我从我们的内容发布者正在使用的API接收到不干净的内容,并且我收到了其中带有非中断空格的p标签,我想删除非中断空格及其所在的p。如果他们在将内容发布到API之前清除内容,那就太好了,但我只需要通过JavaScript或jQuery快速删除它。我在使用下面的代码时遇到了这个错误。"语法错误,无法识别的表达式: "感谢您的帮助。

<p>&nbsp;</p>
$("p").each(function() {
    $(this).find('&nbsp;').remove();
});

选择段落元素,使用.filter()筛选出仅包含&nbsp;的元素,然后使用.remove():

$('p').filter(function(){
   return this.innerHTML == '&nbsp;';
}).remove();

JSFiddle

或者:

$('p').filter(function(){
   return !$.trim($(this).text());
}).remove();

因为.text()为您处理HTML解码,$.trim()删除外部空白,所以它将删除任何只包含空格的段落

<p>&nbsp; &nbsp;&nbsp;</p>
$(p).each(function(){
 $(this).html($(this).html().replace("&nbsp;", ""));
 $(this).replaceTagName(''); 
 // or $(this).contents().unwrap(); much faster
});

这是有效的:

$('p').filter(function () {
    return $(this).html().replace(/&nbsp;/g, '').length === 0
}).remove()

jsFiddle示例

当你说"我想删除非中断空间和它所在的p"时,你只需要删除p,因为这将带走&nbsp;