[英]JavaScript RegExp replace HTML comments
I'm searching a way to replace all html comments from a string like browser does. 我正在寻找一种方法来替换字符串中所有html注释,例如浏览器。 (multilined and unclosed)
(多行和未封闭)
For example, I actually use /(<\\!--[\\s\\S]*?-->)/gim
but if the html comment is unclosed, it does not replace it. 例如,我实际上使用
/(<\\!--[\\s\\S]*?-->)/gim
但是如果未关闭html注释,则不会替换它。
Normally, if the comment tag is not closed, comment tag gets everything after open tag... 通常,如果注释标签未关闭,则注释标签将在打开标签后获取所有内容...
Is there a way to adapt the regexp (or any other regexp) to do the stuff ? 有没有办法使正则表达式(或任何其他正则表达式)适合做这些事情? (in JavaScript)
(在JavaScript中)
This will mark all comments also the one without end tag: <!-- some text -->
这将标记所有注释,也标记没有注释的注释:
<!-- some text -->
<!--[\s\S]*?(?:-->|$)
This will mark all comments also the one without end tag: <!-- some text //-->
这将标记所有注释,也标记没有注释的注释:
<!-- some text //-->
<!--[\s\S]*?(?://-->|$)
This will mark everything from the first <!--
to the very end of the file 这将标记从文件的第一个
<!--
到文件末尾的所有内容
<!--[\s\S]*?(?:$) and regex set to `^$ don't match at line breaks`
This will mark everything from the first <!--
to the end of the line 这将标记从第一行
<!--
到行尾的所有内容
<!--.*
I must agree that using regex like this is not good practice and you shouldn't do it... here's why . 我必须同意,像这样使用正则表达式不是一个好习惯,您不应该这样做。 这就是原因 。
Buuuut, as a matter of understanding regex better, you can make something optional like this: Buuuut,为了更好地了解正则表达式,您可以使诸如此类的可选内容:
/(<\\!--[\\s\\S]*?(?:-->)?)/gim
I wrapped -->
in parenthesis to group it together 我用括号括起来
-->
将其分组在一起
I put a ?
我放一个
?
after that group to make it optional 在该组之后使其成为可选
(not necessary) I put ?:
inside of the group to keep the regex engine from saving a back reference... it's a performance nuance. (不必要)我将
?:
放在组内部,以防止正则表达式引擎保存反向引用...这是性能上的细微差别。
Thanks to @Andie2302 for the help. 感谢@ Andie2302的帮助。
This regexp /<!--[\\s\\S]*?(?:-->|$)/gi
work find. 此正则表达式
/<!--[\\s\\S]*?(?:-->|$)/gi
工作找到。
Do not use the flag m
! 不要使用标志
m
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.