I am trying to write a regex (in JavaScript) that will match a multi line comment at the beginning of a JS file.
So far, I came up with this: /^(\/\*[^\*\/]*\*\/)/g
It works for a single line comment: https://regex101.com/r/ZS5PVI/1
But my problem is that it does not work for a multi line comment: https://regex101.com/r/ZS5PVI/2
Do you have any ideas how to solve it?
Like HTML, JavaScript cannot be parsed by regular expressions. Attempting to do so correctly is futile.
Instead, you must use a parser that will correctly transform JavaScript source code into an AST, which you may inspect programmatically. Fortunately, there’s libraries that do the parsing for you.
Here’s a working example that outputs the AST of this code:
Which gets us:
Now it’s just a matter of looping over the AST and extracting what you need.