[英]Remove HTML comments with Regex, in Javascript
我有一些從 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="--"/> <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]-->
..我使用的正則表達式就是這個
html = html.replace(/<!--(.*?)-->/gm, "")
但是好像沒有匹配,字符串沒有變化。
我缺少什么?
正則表達式/<!--[\\s\\S]*?-->/g
應該可以工作。
您將殺死 CDATA 塊中的轉義文本跨度。
例如
<script><!-- notACommentHere() --></script>
和格式化代碼塊中的文字文本
<xmp>I'm demoing HTML <!-- comments --></xmp>
<textarea><!-- Not a comment either --></textarea>
編輯:
這也不會阻止引入新的評論,如
<!-<!-- A comment -->- not comment text -->
在一輪正則表達式之后將成為
<!-- not comment text -->
如果這是一個問題,您可以轉義<
不是注釋或標簽的一部分(復雜到正確),或者您可以循環並替換如上,直到字符串穩定下來。
這是一個正則表達式,它將根據 HTML-5 規范匹配注釋,包括偽注釋和未關閉的注釋。 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');
這是基於Aurielle Perlmann 的回答,它支持所有情況(單行、多行、未終止和嵌套注釋):
/(<!--.*?-->)|(<!--[\S\s]+?-->)|(<!--[\S\s]*?$)/g
您應該使用/s
修飾符
html = html.replace( /<!--.*?-->/sg
, "")
在 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;
輸出:
hello world!
我最近需要做這件事(即從 html 文件中刪除所有評論)。 這些其他答案沒有考慮到的一些事情;
TLDR:(我只想要刪除所有評論的正則表達式,plz)
/\\\/|\/\s*(?:\\\/|[^\/\*\n])+\/|\\"|"(?:\\"|[^"])*"|\\'|'(?:\\'|[^'])*'|\\`|`(?:\\`|[^`])*`|(\/\/[\s\S]*?$|(?:<!--|\/\s*\*)\s*[\s\S]*?\s*(?:-->|\*\s*\/))/gm
這是一個簡單的演示: https : //www.regexr.com/5fjlu
我不討厭閱讀,剩下的給我看看:
我還需要進行各種其他匹配,這些匹配考慮了包含以其他方式顯示為有效目標的內容的有效字符串。 所以我做了一個類來處理我的各種用途。
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])+\/|\\"|"(?:\\"|[^"])*"|\\'|'(?:\\'|[^'])*'|\\`|`(?:\\`|[^`])*`|/);
}
});
由此,我又創建了兩個類來磨練我需要的兩種主要匹配類型:
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);
}
}
最后(無論它對誰有用)從這個創建的正則表達式:
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');
最后,如果有人願意看到它在使用中。 這是我在其中使用的項目(..我的個人項目始終是 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.