You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式排除空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 p followed 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:55:04