Wolf Wolf - 1 month ago 20
Javascript Question

Javascript regex: find the first 'use strict'

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 =
`
//hi
//there
"use strict";
`;

let match = regex.exec(codeblock);
console.log(match.index);


I'd expect match.index to be 0. However, it actually returns 14, meaning it doesn't recognize my comments. I suspect I didn't use the repeating pattern ()* correctly, but I'm not sure what I should be using?

Answer

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[1]) and the match is found at Position 14, i.e. "use strict".

Replace $ with \r?\n and make sure you have no newline at the start of the test string, and you will get 0:

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).