3

Is there a way in HTML (JavaScript) to write a regular expression to negate an exact string match?

I would like to make sure an input is not equal to "foo". Only "foo" must fail validation, but "fooo" must be allowed.

In other words, I'm looking for a negation of this regex:

<input pattern="^foo$" ...>

Mateusz
  • 2,028
  • 21
  • 23

3 Answers3

5

One possible way is combining start of string anchor (^) with negative lookahead that includes both the target string and end of string anchor ($):

/^(?!foo$)/

Demo.

But pattern pattern is funny in that account - it has to match something in the string, that's why the original approach doesn't work. This does work, however:

<input pattern="(?!foo$).*">
raina77ow
  • 99,006
  • 14
  • 190
  • 222
1

If Javascript is allowed, why not just negate the result of the match?

if (!yourString.match(/^foo$/)) {
    ...
}
Sweeper
  • 176,635
  • 17
  • 154
  • 256
0

You can use this regex:

\bfooo\b
eLRuLL
  • 17,785
  • 8
  • 68
  • 96
karthik selvaraj
  • 396
  • 4
  • 12