Wolf Wolf - 1 year ago 113
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 =
"use strict";

let match = regex.exec(codeblock);

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 Source

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 = 
"use strict";`;
let match = regex.exec(codeblock);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download