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).
The problem is pretty simple really. This will do it:
/^(?!.*foo\.htm$).*\.htm$/i
You could emulate the negative lookbehind with something like
/(.|..|.*[^f]..|.*f[^o].|.*fo[^o])\.htm$/
, but a programmatic approach would be better.String.prototype.endsWith (ES6)
What you are describing (your intention) is a negative look-behind, and Javascript has no support for look-behinds.
Look-aheads look forward from the character at which they are placed — and you've placed it before the
.
. So, what you've got is actually saying "anything ending in.htm
as long as the first three characters starting at that position (.ht
) are notfoo
" which is always true.Usually, the substitute for negative look-behinds is to match more than you need, and extract only the part you actually do need. This is hacky, and depending on your precise situation you can probably come up with something else, but something like this:
As mentioned JavaScript does not support negative look-behind assertions.
But you could use a workaroud:
This will match everything that ends with
.htm
but it will store"foo"
intoRegExp.$1
if it matchesfoo.htm
, so you can handle it separately.Like Renesis mentioned, "lookbehind" is not supported in JavaScript, so maybe just use two regexps in combination: