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

4

7

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
Narial answered 11/2, 2017 at 13:42 Comment(1)
Not looked at webpack in a long time but I seem to remember that you can skip the regular expression and pass a function instead. Something like this in your case: function (path) { return path.endsWith('.js') && !path.endsWith('test.js')} I could be mixing this up with some other bundler though.Germicide
C
2

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"));
Canikin answered 11/2, 2017 at 14:1 Comment(0)
G
7

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.
Grizel answered 11/2, 2017 at 13:59 Comment(1)
My bad for disrupting your answer again, this is actually the best regex presented (ie the only one to have the end-of-line positional in the lookahead to not catch mid-string test.js )Dejected
C
2

Javascript doesn't support negative lookbehinds, but lookarounds:

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

DEMO

Coverup answered 11/2, 2017 at 13:45 Comment(0)
C
2

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"));
Canikin answered 11/2, 2017 at 14:1 Comment(0)
B
-1

This may help:

^(?!.*\..*\.js$).*\.js$
Blasien answered 8/8, 2024 at 8:31 Comment(1)
This does not address the question which is about excluding test files.Coulter

© 2022 - 2025 — McMap. All rights reserved.