简体   繁体   English

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

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

Suppose I have a HTML comment like this:假设我有这样的 HTML 评论:

<!--hello world-->

We can get the get the comment with this regex:我们可以用这个正则表达式得到评论:

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

Working example:工作示例:

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

But if the comment is multi-line, like this:但是如果注释是多行的,像这样:

<!--hello
world-->

Then the regex doesn't work.然后正则表达式不起作用。

 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>

How can I select the multi-line HTML comment?我如何 select 多行 HTML 评论?

You just need a newline symbol along with any char.你只需要一个换行符和任何字符。 like this -像这样 -

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

Use pattern [\s\S]* instead of .* to catch all chars, including whitespace.使用模式[\s\S]*而不是.*来捕获所有字符,包括空格。 Alternatively, use the m flag if you want the .* match also newlines.或者,如果您希望.*也匹配换行符,请使用m标志。

Use non-greedy pattern [\s\S]*?使用非贪婪模式[\s\S]*? if you expect more than one <.--...--> pattern.如果您期望多个<.--...-->模式。

Working test case:工作测试用例:

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

Output: Output:

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

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

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