如何用正则表达式排除空p标签,仅移除其他空HTML标签?
Great question! To preserve empty <p> tags while stripping all other empty elements from your HTML string, you can modify your regex with a negative lookahead to exclude the p tag. Here's the adjusted code:
let s = "<h1>test</h1><h1></h1><p>a</p><p></p><h2></h2>"; s = s.trim().replace( /<(?!p\b)(\w*)\s*[^\/>]*>\s*<\/\1>/g, '' ) console.log(s); // Output: "<h1>test</h1><p>a</p><p></p>"
How it works:
The key change is adding (?!p\b) immediately after the opening < in the regex. This is a negative lookahead that tells the regex:
- "Do NOT match this opening tag if it starts with
pfollowed by a word boundary (\b)" - The word boundary ensures we don't accidentally exclude similar tags like
<pre>or<progress>
The rest of the regex behaves as before:
(\w*)captures the tag name to ensure we match the corresponding closing tag\s*[^\/>]*accounts for optional whitespace and attributes in the opening tag\s*<\/\1>matches the closing tag (allowing for any whitespace inside the empty tag)
This modification will keep your empty <p> tags intact while removing all other empty elements like the empty <h1> and <h2> in your sample input.
内容的提问来源于stack exchange,提问作者totalnoob
相关产品推荐
相关产品推荐

