我想选择所有空标签,要么是独立的,要么是嵌套的,而不是其他标签。例如,regex应该匹配如下:
<p></p>
<p><strong><em></em></strong></p>
<p style="background: black;"><span></span></p>
但不是这个:
<p>text</p>
<p><strong><em>text</em></strong></p>
<p style="background: black;"><span>text</span></p>
在像<p><span style="background-color: red;"></span>some text </p>
这样棘手的情况下,它应该匹配<span style="background-color: red;"></span>
。
这就是我现在使用的:<[^<p>'/>][^>]*><'/[^>]+>
然而,它遗漏了<p><strong><em></em></strong></p>
等情况,其中有多个嵌套的标签。
谢谢!
这个版本应该找到空段落和段落内的空嵌套标签。它可以工作到3个嵌套标签的级别。
function emptyNestedTags(str)
{
var match = str.match(/<('w+)(?:'s[^>]*)?>(?:<('w+)(?:'s[^>]*)?>(?:<('w+)(?:'s[^>]*)?><'/'3>)?<'/'2>)?<'/'1>/);
if (match) return match[0]; else return "no empty tags found";
}
alert(emptyNestedTags("<p id='"id'"></p>"));
alert(emptyNestedTags("<p id='"id'">SOME TEXT</p>"));
alert(emptyNestedTags("<p><em id='"id'"></em></p>"));
alert(emptyNestedTags("<p><em id='"id'">SOME TEXT</em></p>"));
alert(emptyNestedTags("<p><em id='"id'"></em>SOME TEXT </p>"));
alert(emptyNestedTags("<p><span style='"background-color: red;'"><em></em></span></p>"));
alert(emptyNestedTags("<p><span style='"background-color: red;'"><em>TEXT</em></span></p>"));
alert(emptyNestedTags("<p><span style='"background-color: red;'"><em></em></span> TEXT</p>"));
如果您不想检查结束标记是否与开始标记匹配(为什么要这样做,真的?),它更简单,不需要捕获组:
function emptyNestedTags(str)
{
return str.match(/<'w+(?:'s[^>]*)?>(?:<'w+(?:'s[^>]*)?>(?:<'w+(?:'s[^>]*)?><'/'w+>)?<'/'w+>)?<'/'w+>/);
}
alert(emptyNestedTags("<p id='"id'"></p>"));
alert(emptyNestedTags("<p id='"id'">SOME TEXT</p>"));
alert(emptyNestedTags("<p><em id='"id'"></em></p>"));
alert(emptyNestedTags("<p><em id='"id'">SOME TEXT</em></p>"));
alert(emptyNestedTags("<p><em id='"id'"></em>SOME TEXT </p>"));
alert(emptyNestedTags("<p><span style='"background-color: red;'"><em></em></span></p>"));
alert(emptyNestedTags("<p><span style='"background-color: red;'"><em>TEXT</em></span></p>"));
alert(emptyNestedTags("<p><span style='"background-color: red;'"><em></em></span> TEXT</p>"));