Negative lookahead Regular Expression

gilly3 picture gilly3 · Jul 28, 2011 · Viewed 47.5k times · Source

I want to match all strings ending in ".htm" unless it ends in "foo.htm". I'm generally decent with regular expressions, but negative lookaheads have me stumped. Why doesn't this work?

/(?!foo)\.htm$/i.test("/foo.htm");  // returns true. I want false.

What should I be using instead? I think I need a "negative lookbehind" expression (if JavaScript supported such a thing, which I know it doesn't).

Answer

ridgerunner picture ridgerunner · Jul 28, 2011

The problem is pretty simple really. This will do it:

/^(?!.*foo\.htm$).*\.htm$/i