最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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
ponent.js      // <-- should match
ponent.test.js // <-- should not match

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
ponent.js      // <-- should match
ponent.test.js // <-- should not match
Share Improve this question asked Feb 11, 2017 at 13:42 David CDavid C 2,0382 gold badges17 silver badges34 bronze badges 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. – Karl-Johan Sjögren Commented Feb 11, 2017 at 13:58
Add a ment  | 

4 Answers 4

Reset to default 7

There you go:

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

See it working on regex101..


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

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"));

Javascript doesn't support negative lookbehinds, but lookarounds:

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

DEMO

This may help:

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论