使用RegEx删除空标签 [英] Remove empty tags using RegEx
问题描述
我想删除空标记,例如< label>< / label>
,< font> < / font>
以便:
I want to delete empty tags such as <label></label>
, <font> </font>
so that:
<label></label><form></form>
<p>This is <span style="color: red;">red</span>
<i>italic</i>
</p>
将被清理为:
<p>This is <span style="color: red;">red</span>
<i>italic</i>
</p>
我在javascript中有这个RegEx,但它删除了空标签,但它也删除了这个: code>< i> italic< / i>< / p>
I have this RegEx in javascript, but it deletes the the empty tags but it also delete this: "<i>italic</i></p>"
str=str.replace(/<[\S]+><\/[\S]+>/gim, "");
我缺少什么?
推荐答案
你的字符类有not spaces,意思是< i> italic< / i>< / p>
会匹配。正则表达式的前半部分将匹配<(i> italic< / i)>
和下半部分< /( p)GT;
。 (我用括号表示每个 [\ S] +
匹配。)
You have "not spaces" as your character class, which means "<i>italic</i></p>
" will match. The first half of your regex will match "<(i>italic</i)>
" and the second half "</(p)>
". (I've used brackets to show what each [\S]+
matches.)
更改此:
/<[\S]+><\/[\S]+>/
对此:
/<[^\/>][^>]*><\/[^>]+>/
总的来说,你应该使用正确的HTML处理器,但是如果你正在使用HTML汤,这应该足够了:)
Overall you should really be using a proper HTML processor, but if you're munging HTML soup this should suffice :)
这篇关于使用RegEx删除空标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!