stripHtmlComments function
Strip block-level HTML comments from markdown content.
Uses simple detection to identify comments at the block level only. Inline HTML comments inside a paragraph are left intact. Unclosed comments are left in place.
Implementation
({String content, bool stripped}) stripHtmlComments(String content) {
if (!content.contains('<!--')) {
return (content: content, stripped: false);
}
final commentPattern = RegExp(r'<!--[\s\S]*?-->');
final lines = content.split('\n');
final result = StringBuffer();
bool stripped = false;
for (int i = 0; i < lines.length; i++) {
final line = lines[i];
final trimmed = line.trimLeft();
if (trimmed.startsWith('<!--') && trimmed.contains('-->')) {
final residue = line.replaceAll(commentPattern, '');
stripped = true;
if (residue.trim().isNotEmpty) {
result.writeln(residue);
}
} else {
result.writeln(line);
}
}
return (content: result.toString(), stripped: stripped);
}