I'd like to determine whether the file begins with zero or more single-line comments (the // style), followed by "use strict".
Here's my attempt:
var regex = new RegExp("(\/\/.*$)*\"use strict\";", 'm');
var codeblock =
let match = regex.exec(codeblock);
The point is that your
(\/\/.*\r?\n)* part does not match the comments since you are not consuming the linebreaks, you only assert their presence with
$. Thus, Group 0 value is undefined (try printing
match) and the match is found at Position 14, i.e.
\r?\n and make sure you have no newline at the start of the test string, and you will get
var regex = /(\/\/.*\r?\n)*\"use strict\";/m; var codeblock = `//hi //there "use strict";`; let match = regex.exec(codeblock); console.log(match.index);
I also suggest using a regex literal notation
/(\/\/.*\r?\n)*\"use strict\";/m rather than the RegExp constructor notation since your pattern is static (no variables are used to build the regex).