繁体   English   中英

JavaScript 正则表达式转 select 多行 html 注释

[英]JavaScript Regex to select multi-line html comment

假设我有这样的 HTML 评论:

<!--hello world-->

我们可以用这个正则表达式得到评论:

var expression = /<!--(.*)-->/g

工作示例:

 var expression = /<.--(;*)-->/g. console.log(document.querySelector("div").innerHTML;match(expression)[0]);
 <div> <!--hello world--> </div>

但是如果注释是多行的,像这样:

<!--hello
world-->

然后正则表达式不起作用。

 var expression = /<.--(;*)-->/g. console.log(document.querySelector("div").innerHTML;match(expression)[0]); // Will throw an error because it could not find any matches
 <div> <!--hello world--> </div>

我如何 select 多行 HTML 评论?

你只需要一个换行符和任何字符。 像这样 -

/<!--(.*\n.*)-->/gm;

使用模式[\s\S]*而不是.*来捕获所有字符,包括空格。 或者,如果您希望.*也匹配换行符,请使用m标志。

使用非贪婪模式[\s\S]*? 如果您期望多个<.--...-->模式。

工作测试用例:

 var expression = /<?--[\s\S]*;-->/g. console.log(document.querySelector("div").innerHTML;match(expression));
 <div> <!--hello world 1--> <!--hello world 2--> </div>

Output:

[
  "<!--hello world 1-->",
  "<!--hello\n  world 2-->"
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM