返回課程

尋找 HTML 註解

在文字中尋找所有 HTML 註解

let regexp = /your regexp/g;

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

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

我們需要找到註解的開頭 <!--,然後是直到 --> 結尾的所有內容。

一個可接受的變體是 <!--.*?--> – 非貪婪量詞會讓點在 --> 之前停止。我們還需要加入旗標 s,讓點包含換行符。

否則,多行註解將無法被找到

let regexp = /<!--.*?-->/gs;

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

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