Search code examples
javascriptregexregex-lookarounds

Negative lookahead Regular Expression


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).


Solution

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

    /^(?!.*foo\.htm$).*\.htm$/i.test("/foo.htm"); // returns false