Back to the lesson

Find HTML comments

Find all HTML comments in the text:

let reg = /your regexp/g;

let str = `... <!-- My -- comment
 test --> ..  <!----> ..
`;

alert( str.match(reg) ); // '<!-- My -- comment \n test -->', '<!---->'

We need to find the beginning of the comment <!--, then everything till the end of -->.

The first idea could be <!--.*?--> – the lazy quantifier makes the dot stop right before -->.

But a dot in Javascript means “any symbol except the newline”. So multiline comments won’t be found.

We can use [\s\S] instead of the dot to match “anything”:

let reg = /<!--[\s\S]*?-->/g;

let str = `... <!-- My -- comment
 test --> ..  <!----> ..
`;

alert( str.match(reg) ); // '<!-- My -- comment \n test -->', '<!---->'