简体   繁体   English

如果是html标签,则替换段落标签之间的任何内容

[英]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. 我需要从粘贴到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. 因此,正则表达式不起作用-该段落尽管不包含实际文本,但确实包含html标签。

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. 现在任何人都可以告诉我修改我的正则表达式,以便它不仅可以用空字符串替换不带任何内容的段落,而且可以替换仅包含html标记的段落。

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>

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM