-2

Suppose I have a HTML comment like this:

<!--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?

Caleb Liu
  • 627
  • 5
  • 18
  • Try adding \r\n in your expression, if that doesn't work search for line breaks in regex. That's really the key issue, matching line break in the middle of the pattern. – WPW Sep 14 '22 at 15:48

2 Answers2

0

You just need a newline symbol along with any char. like this -

/<!--(.*\n.*)-->/gm;
  • With the `m` flag the `.` matches also newlines, so `//gm;` would be sufficient. However, it fails if there are multiple `` patterns. Also, with `//gm;` you would get a no-match if the HTML comment has no newline. – Peter Thoeny Sep 15 '22 at 00:43
  • FYI - The ask was for multiline only. – Rahul Kumar Oct 20 '22 at 18:27
0

Use pattern [\s\S]* instead of .* to catch all chars, including whitespace. Alternatively, use the m flag if you want the .* match also newlines.

Use non-greedy pattern [\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:

[
  "<!--hello world 1-->",
  "<!--hello\n  world 2-->"
]
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20