[英]Remove HTML comments with Regex, in Javascript
I've got some ugly HTML generated from Word, from which I want to strip all HTML comments.我有一些从 Word 生成的难看的 HTML,我想从中删除所有 HTML 注释。
The HTML looks like this: 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="--"/> <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.但是好像没有匹配,字符串没有变化。
What I am missing?我缺少什么?
The regex /<!--[\\s\\S]*?-->/g
should work.正则表达式
/<!--[\\s\\S]*?-->/g
应该可以工作。
You're going to kill escaping text spans in CDATA blocks.您将杀死 CDATA 块中的转义文本跨度。
Eg例如
<script><!-- notACommentHere() --></script>
and literal text in formatted code blocks和格式化代码块中的文字文本
<xmp>I'm demoing HTML <!-- comments --></xmp>
<textarea><!-- Not a comment either --></textarea>
EDIT:编辑:
This also won't prevent new comments from being introduced as in这也不会阻止引入新的评论,如
<!-<!-- A comment -->- not comment text -->
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.如果这是一个问题,您可以转义
<
不是注释或标签的一部分(复杂到正确),或者您可以循环并替换如上,直到字符串稳定下来。
Here's a regex that will match comments including psuedo-comments and unclosed comments per the HTML-5 spec.这是一个正则表达式,它将根据 HTML-5 规范匹配注释,包括伪注释和未关闭的注释。 The CDATA section are only strictly allowed in foreign XML.
CDATA 部分只在外部 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');
This is based off Aurielle Perlmann's answer , it supports all cases (single-line, multi-line, un-terminated, and nested comments):这是基于Aurielle Perlmann 的回答,它支持所有情况(单行、多行、未终止和嵌套注释):
/(<!--.*?-->)|(<!--[\S\s]+?-->)|(<!--[\S\s]*?$)/g
https://regex101.com/r/az8Lu6/1 https://regex101.com/r/az8Lu6/1
You should use the /s
modifier您应该使用
/s
修饰符
html = html.replace( /<!--.*?-->/sg
, "") html = html.replace(
/<!--.*?-->/sg
, "")
Tested in perl:在 perl 中测试:
use strict;
use warnings;
my $str = 'hello <!--[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]-->world!';
$str =~ s/<!--.*?-->//sg;
print $str;
Output:输出:
hello world!
I recently needed to do this very thing (ie Remove all comments from a html file).我最近需要做这件事(即从 html 文件中删除所有评论)。 Some things that these other answers don't take into consideration;
这些其他答案没有考虑到的一些事情;
TLDR: (I just want the regex that removes all the comments, plz) TLDR:(我只想要删除所有评论的正则表达式,plz)
/\\\/|\/\s*(?:\\\/|[^\/\*\n])+\/|\\"|"(?:\\"|[^"])*"|\\'|'(?:\\'|[^'])*'|\\`|`(?:\\`|[^`])*`|(\/\/[\s\S]*?$|(?:<!--|\/\s*\*)\s*[\s\S]*?\s*(?:-->|\*\s*\/))/gm
And here is a simple demo: https://www.regexr.com/5fjlu这是一个简单的演示: https : //www.regexr.com/5fjlu
I don't hate reading, show me the rest:我不讨厌阅读,剩下的给我看看:
I also needed to do various other matching that took into account valid strings containing things that otherwise appear as valid targets.我还需要进行各种其他匹配,这些匹配考虑了包含以其他方式显示为有效目标的内容的有效字符串。 So I made a class to handle my variety of uses.
所以我做了一个类来处理我的各种用途。
class StringAwareRegExp extends RegExp {
static get [Symbol.species]() { return RegExp; }
constructor(regex, flags){
if(regex instanceof RegExp) regex = StringAwareRegExp.prototype.regExpToInnerRegexString(regex);
regex = super(`${StringAwareRegExp.prototype.disqualifyStringsRegExp}(${regex})`, flags);
return regex;
}
stringReplace(sourceString, replaceString = ''){
return sourceString.replace(this, (match, group1) => { return group1 === undefined ? match : replaceString; });
}
}
StringAwareRegExp.prototype.regExpToInnerRegexString = function(regExp){ return regExp.toString().replace(/^\/|\/[gimsuy]*$/g, ''); };
Object.defineProperty(StringAwareRegExp.prototype, 'disqualifyStringsRegExp', {
get: function(){
return StringAwareRegExp.prototype.regExpToInnerRegexString(/\\\/|\/\s*(?:\\\/|[^\/\*\n])+\/|\\"|"(?:\\"|[^"])*"|\\'|'(?:\\'|[^'])*'|\\`|`(?:\\`|[^`])*`|/);
}
});
From this I created two more classes to hone in on the 2 major types of matches I needed:由此,我又创建了两个类来磨练我需要的两种主要匹配类型:
class CommentRegExp extends StringAwareRegExp {
constructor(regex, flags){
if(regex instanceof RegExp) regex = StringAwareRegExp.prototype.regExpToInnerRegexString(regex);
return super(`\\/\\/${regex}$|(?:<!--|\\/\\s*\\*)\\s*${regex}\\s*(?:-->|\\*\\s*\\/)`, flags);
}
}
class StatementRegExp extends StringAwareRegExp {
constructor(regex, flags){
if(regex instanceof RegExp) regex = StringAwareRegExp.prototype.regExpToInnerRegexString(regex);
return super(`${regex}\\s*;?\\s*?`, flags);
}
}
And finally (however useful it may be to whomever) the regex created from this:最后(无论它对谁有用)从这个创建的正则表达式:
const allCommentsRegex = new CommentRegExp(/[\s\S]*?/, 'gm');
const enableBabelRegex = new CommentRegExp(/enable-?_?\s?babel/, 'gmi');
const disableBabelRegex = new CommentRegExp(/disable-?_?\s?babel/, 'gmi');
const includeRegex = new CommentRegExp(/\s*(?:includes?|imports?|requires?)\s+(.+?)/, 'gm');
const importRegex = new StatementRegExp(/import\s+(?:(?:\w+|{(?:\s*\w\s*,?\s*)+})\s+from)?\s*['"`](.+?)['"`]/, 'gm');
const requireRegex = new StatementRegExp(/(?:var|let|const)\s+(?:(?:\w+|{(?:\s*\w\s*,?\s*)+}))\s*=\s*require\s*\(\s*['"`](.+?)['"`]\s*\)/, 'gm');
const atImportRegex = new StatementRegExp(/@import\s*['"`](.+?)['"`]/, 'gm');
And lastly, if anyone cares to see it in use.最后,如果有人愿意看到它在使用中。 Here's the project I used it in (..My personal projects are always a WIP..): https://github.com/fatlard1993/page-compiler
这是我在其中使用的项目(..我的个人项目始终是 WIP..): https : //github.com/fatlard1993/page-compiler
const regex = /<!--(.*?)-->/gm; const str = `You will be able to see this text. <!-- You will not be able to see this text. --> You can even comment out things in <!-- the middle of --> a sentence. <!-- Or you can comment out a large number of lines. --> <div class="example-class"> <!-- Another --> thing you can do is put comments after closing tags, to help you find where a particular element ends. <br> (This can be helpful if you have a lot of nested elements.) </div> <!-- /.example-class -->`; const subst = ``; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result);
html = html.replace("(?s)<!--\\[if(.*?)\\[endif\\] *-->", "")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.