David C
David C

Reputation: 2038

How can I get a regular expression to match files ending in ".js" but not ".test.js"?

I am using webpack which takes regular expressions to feed files into loaders. I want to exclude test files from build, and the test files end with .test.js. So, I am looking for a regular expression that would match index.js but not index.test.js.

I tried to use a negative lookback assertion with

/(?<!\.test)\.js$/

but it says that the expression is invalid.

SyntaxError: Invalid regular expression: /(?<!\.test)\.js$/: Invalid group

example files names:

index.js          // <-- should match
index.test.js     // <-- should not match
component.js      // <-- should match
component.test.js // <-- should not match

Upvotes: 7

Views: 7207

Answers (4)

F1xGOD
F1xGOD

Reputation: 1

This may help:

^(?!.*\..*\.js$).*\.js$

Upvotes: -1

Jan
Jan

Reputation: 43169

There you go:

^(?!.*\.test\.js$).*\.js$

See it working on regex101.com.


As mentioned by others, the regex engine used by JavaScript does not support all features. For example, negative lookbehinds are not supported.

Upvotes: 7

Sagar V
Sagar V

Reputation: 12478

var re=/^(?!.*test\.js).*\.js$/;
console.log(re.test("index.test.js"));
console.log(re.test("test.js"));
console.log(re.test("someother.js"));
console.log(re.test("testt.js"));

Upvotes: 2

baao
baao

Reputation: 73241

Javascript doesn't support negative lookbehinds, but lookarounds:

^((?!\.test\.).)*\.js$

DEMO

Upvotes: 2

Related Questions