Justin
Justin

Reputation: 566

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

So I am receiving unclean content from an API that our content publishers are using and I am getting P tags with non-breaking spaces inside of them and I want to remove the non-breaking space and the P it is in. It would be nice if they cleaned up their content before they published it to the API, but I just need a quick way to remove this via JavaScript or jQuery. I get this error when using the code below. "Syntax error, unrecognized expression:  " Thanks for any help.

<p>&nbsp;</p>

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

Upvotes: 0

Views: 2938

Answers (3)

George
George

Reputation: 36784

Select your paragraph elements, filter out the ones that contain only &nbsp; using .filter(), then use .remove():

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

JSFiddle

Or:

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

Which, because .text() handles HTML decoding for you and $.trim() removes outer whitespace, will remove any paragraph that contains only spaces I.E

<p>&nbsp; &nbsp;&nbsp;</p>

Upvotes: 6

j08691
j08691

Reputation: 207901

This works:

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

jsFiddle example

While you said "I want to remove the non-breaking space and the P it is in", you only need to remove the P since that will take the &nbsp; with it.

Upvotes: 0

void
void

Reputation: 36703

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

Upvotes: 1

Related Questions