First thing, your comment matching regex can be reduced to this:
/\/\*\*(\S|\s)*?\*\//g
but this may be better if you're search for more than one:
/\/\*\*(?:(\S|\s)(?!\*\/))*?(\S|\s)\*\//g
Second, you may have to do this in two parts:
Step 1: Use {string}.match()
to create an array of all your matched functions.
Step 2: Use {string}.split()
to remove all matched functions, leaving the rest of the code. You can then also use .map()
to break it down.
Something like this:
var functions = code.match(funcRegex);
var restOfCode = code.split(funcRegex).map(c=>c.match(/\/\*\*(?:(\S|\s)(?!\*\/))*?(\S|\s)\*\//g));
Note: Each item of restOfCode
will be an array of comments found, and the last one should be the one just before the function. For example, for function body functions[0]
, you would check if the last item in the array restOfCode[0][restOfCode[0].length-1]
starts and ends with '/**' and '*/'.
Warning: Most regexes cannot protected against some cases, like this, or similar:
var b=`
function(){ }
`;
No regex will be foolproof for what you want to do, but can help break code up into parts to parse properly. For simple cases though it may be fine.
BTW: You did ask to "join them both" but did not clearly give BOTH regexes here in your question. Yes, I know the link as them already combined, but it should be clear in your question.
Since parsing function bodies with a regex is a fool's errand, so to speak, here is one that at least matches comments with the start of what appears to be a function start:
/^(\/\*\*(?:(?:\S|\s)(?!\*\/))*?(?:\S|\s)?\*\/\s*)?((?:(?:const|var|let).*{.*})?[^}\n]*(?:\(.*\).*{))/gm
https://regex101.com/r/WGqfm8/15
Group 1 returns the doc comment, if exists, and group 2 the function start line.