在Javascript中使用Regex删除HTML注释

rod*_*dbv 40 javascript regex

我从Word生成了一些丑陋的HTML,我想从中删除所有HTML注释.

HTML看起来像这样:

<!--[if gte mso 9]><xml> <o:OfficeDocumentSettings> <o:RelyOnVML/> <o:AllowPNG/> </o:OfficeDocumentSettings> </xml><![endif]--><!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:TrackMoves/> <w:TrackFormatting/> <w:HyphenationZone>21</w:HyphenationZone> <w:PunctuationKerning/> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:DoNotPromoteQF/> <w:LidThemeOther>NO-BOK</w:LidThemeOther> <w:LidThemeAsian>X-NONE</w:LidThemeAsian> <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript> <w:Compatibility> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> <w:SplitPgBreakAndParaMark/> <w:EnableOpenTypeKerning/> <w:DontFlipMirrorIndents/> <w:OverrideTableStyleHps/> </w:Compatibility> <m:mathPr> <m:mathFont m:val="Cambria Math"/> <m:brkBin m:val="before"/> <m:brkBinSub m:val="&#45;-"/> <m:smallFrac m:val="off"/> <m:dispDef/> <m:lMargin m:val="0"/> <m:rMargin m:val="0"/> <m:defJc m:val="centerGroup"/> <m:wrapIndent m:val="1440"/> <m:intLim m:val="subSup"/> <m:naryLim m:val="undOvr"/> </m:mathPr></w:WordDocument> </xml><![endif]-->
Run Code Online (Sandbox Code Playgroud)

..我正在使用的正则表达式就是这个

html = html.replace(/<!--(.*?)-->/gm, "")
Run Code Online (Sandbox Code Playgroud)

但似乎没有匹配,字符串不变.

我错过了什么?

Mik*_*uel 78

正则表达式/<!--[\s\S]*?-->/g应该工作.

您将要杀死CDATA块中的转义文本范围.

例如

<script><!-- notACommentHere() --></script>
Run Code Online (Sandbox Code Playgroud)

和格式化代码块中的文字文本

<xmp>I'm demoing HTML <!-- comments --></xmp>

<textarea><!-- Not a comment either --></textarea>
Run Code Online (Sandbox Code Playgroud)

编辑:

这也不会阻止新的评论被引入

<!-<!-- A comment -->- not comment text -->
Run Code Online (Sandbox Code Playgroud)

经过一轮正则表达式之后

<!-- not comment text -->
Run Code Online (Sandbox Code Playgroud)

如果这是一个问题,您可以转义<不是注释或标记的一部分(复杂到正确),或者您可以如上所述循环和替换,直到字符串稳定下来.


这是一个正则表达式,它将匹配HTML-5规范中包含psuedo-comments和unclosed comments的注释.CDATA部分仅在外部XML中严格允许.这遭受与上述相同的警告.

var COMMENT_PSEUDO_COMMENT_OR_LT_BANG = new RegExp(
    '<!--[\\s\\S]*?(?:-->)?'
    + '<!---+>?'  // A comment with no body
    + '|<!(?![dD][oO][cC][tT][yY][pP][eE]|\\[CDATA\\[)[^>]*>?'
    + '|<[?][^>]*>?',  // A pseudo-comment
    'g');
Run Code Online (Sandbox Code Playgroud)


Zac*_*ist 5

这是基于Aurielle Perlmann 的回答,它支持所有情况(单行、多行、未终止和嵌套注释):

/(<!--.*?-->)|(<!--[\S\s]+?-->)|(<!--[\S\s]*?$)/g
Run Code Online (Sandbox Code Playgroud)

https://regex101.com/r/az8Lu6/1

regex101 输出