1

As the title states: Can any one help me figure out how to write a JavaScript regex expression that matches a string that end in ".js" but fails when given a string that ends in "-min.js".

Examples:

hello.js -> match

hellomin.js -> match

hello-min.js -> no match

hello-min-hello.js -> match

Thanks!

Sidawy
  • 574
  • 1
  • 3
  • 17

5 Answers5

3

Use negative lookahead:

(?!-min)[\w-]{4}\.js$

Update

This will also work for less than 4 characters before the .js:

(?:(?!-min)[\w-]{4}|^[\w-]{1,3})\.js$

robinCTS
  • 5,746
  • 14
  • 30
  • 37
2

Use the pseudo-inverted matching based on a previous question:

^((?!-min\.).)*\.js$
Community
  • 1
  • 1
oleq
  • 15,697
  • 1
  • 38
  • 65
0

Since JS does not support negative lookbehind, lets use negative lookahead!

var str = 'asset/34534534/jquery.test-min.js',
    reversed = str.split('').reverse().join('');

// And now test it
/^sj\.(?!nim-)/.test(reversed); // will give you false if str has min.js at the end

Funny, right?

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

I have extended @robinCTS's regex to match file paths with more than one dot (for example with version number at the end of filename) and also a string that ends in ".min.js":

(?:(?!(-|\.)min)[\w\.-]{4}|^[\w\.-]{1,3})\.js$

Examples:

  • hello.js -> match
  • hellomin.js -> match
  • hellomin-2.4.3.js -> match
  • hello-min-hello.js -> match
  • hello-min.js -> no match
  • hello.min.js -> no match
  • hellomin-2.4.3-min.js -> no match
  • hellomin-2.4.3.min.js -> no match
-1

You can use negative lookbehind :

(?<!-min)\.js$

Example

Pilou
  • 1,398
  • 13
  • 24