Sidawy
Sidawy

Reputation: 574

JavaScript Regex to find string that ends in ".js" but not "-min.js"

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!

Upvotes: 1

Views: 1703

Answers (5)

Michał Mańko
Michał Mańko

Reputation: 1

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

Upvotes: 0

robinCTS
robinCTS

Reputation: 5886

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$

Upvotes: 3

oleq
oleq

Reputation: 15895

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

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

Upvotes: 2

dfsq
dfsq

Reputation: 193271

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?

Upvotes: 0

Pilou
Pilou

Reputation: 1478

You can use negative lookbehind :

(?<!-min)\.js$

Example

Upvotes: -1

Related Questions