Q:

Replace anything between paragraph tags if it is a html tag

I need to remove empty paragraphs from a string which is being pasted into a html textarea. I have this as a regular expression to do that.
var reg = /\<p( [a-zA-Z]*=((\"[^\"]*\")|(\'[^\']*\')))*\>\<\/p\>/g;

and it works okay. But, some of the data being pasted contains paragraphs that look like this.
<p><b></b></p>

So the regular expression does not work - as the paragraph, although it contains no actual text, does contain html tags.
Can anyone tell me please now to modify my regular expression so that it will not only replace paragraphs with no content with an empty string, but will also replace paragraphs where the only content is html tags.
At the moment text like this.
<p style="margin:0px;"></p>
<p>Fred</p>
<p style="margin-left:10px;"></p>
<p><b></b></p>
<p>Jim</p>

is being modified so it then becomes
<p>Fred></p>
<p><b></b></p>
<p>Jim</p>

I need it to become
<p>Fred</p>
<p>Jim</p>

A:

You can try this:
<p[^>]*>(?:\s*<(\w+)>\s*<\/\1>\s*|\s*)<\/p>

and replace by empty
Regex Demo

const regex = /<p[^>]*>(?:\s*<(\w+)>\s*<\/\1>\s*|\s*)<\/p>/g;
const str = `<p style="margin:0px;"></p>
<p>Fred</p>
<p style="margin-left:10px;"></p>
<p><b></b></p>
<p>Jim</p>`;
const subst = ``;
const result = str.replace(regex, subst);

console.log(result);

