CodexBloom - Programming Q&A Platform

Regex Not Capturing Comments in Markdown Files Using JavaScript

👀 Views: 41 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
regex markdown node.js JavaScript

Quick question that's been bugging me - I'm currently trying to parse a Markdown file in a Node.js application to extract comments that start with `<!--` and end with `-->`. However, my regex seems to unexpected result at capturing comments that are placed on a single line or when they are embedded between other content. Here's the regex I wrote: ```javascript const regex = /<!--(.*?)-->/gs; ``` When I test it against the following sample Markdown content: ``` # Title Some text here. <!-- This is a comment --> More text <!-- Another comment --> ``` I expect to capture both comments, but when I run the following JavaScript code: ```javascript const fs = require('fs'); const markdownContent = fs.readFileSync('sample.md', 'utf-8'); const comments = markdownContent.match(regex); console.log(comments); ``` I get `null` instead of an array of comments. I've also tried using `g` and `s` flags, but I'm not sure if I have the right approach. Could the scenario be with my regex not handling newlines correctly? Any suggestions on how to properly capture comments in different scenarios, including comments near other Markdown elements or multiple comments on the same line? I've checked the Markdown specification, and my regex should technically work, but I must be missing something in implementation. For context: I'm using Javascript on macOS. What am I doing wrong?