在Javascript中使用Regex删除HTML注释 [英] Remove HTML comments with Regex, in Javascript
问题描述
我从Word生成了一些丑陋的HTML,我想从中删除所有HTML注释。
I've got some ugly HTML generated from Word, from which I want to strip all HTML comments.
HTML看起来像这样:
The HTML looks like this:
<!--[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="--"/> <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]-->
..我正在使用的正则表达式是这一个
..and the regex I am using is this one
html = html.replace(/<!--(.*?)-->/gm, "")
但似乎没有匹配,字符串不变。
But there seems to be no match, the string is unchanged.
我是什么我失踪了?
推荐答案
正则表达式 /<! - [\\\\ S] *? - > / g
应该有效。
你要杀死转义文本范围。
例如
<script><!-- notACommentHere() --></script>
和格式化代码块中的文字文本
and literal text in formatted code blocks
<xmp>I'm demoing HTML <!-- comments --></xmp>
<textarea><!-- Not a comment either --></textarea>
编辑:
这也赢了' t阻止引入新评论
This also won't prevent new comments from being introduced as in
<!-<!-- A comment -->- not comment text -->
在一轮regexp之后会变成
which after one round of that regexp would become
<!-- not comment text -->
如果这是一个问题,你可以逃避<
不是注释或标记的一部分(很难得到)或者你可以循环和替换,如上所述直到字符串稳定下来。
If this is a problem, you can escape <
that are not part of a comment or tag (complicated to get right) or you can loop and replace as above until the string settles down.
这是一个匹配评论的正则表达式,包括 psuedo-comments 和HTML-5规范中未公开的评论。 CDATA部分仅在外部XML中严格允许。这会遇到与上述相同的警告。
Here's a regex that will match comments including psuedo-comments and unclosed comments per the HTML-5 spec. The CDATA section are only strictly allowed in foreign XML. This suffers the same caveats as above.
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');
这篇关于在Javascript中使用Regex删除HTML注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!