5

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,340
  • 25
  • 24

3 Answers3

7

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
  • 103,633
  • 15
  • 192
  • 229
1

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

if (!yourString.match(/^foo$/)) {
    ...
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

You can use this regex:

\bfooo\b
eLRuLL
  • 18,488
  • 9
  • 73
  • 99
karthik selvaraj
  • 426
  • 5
  • 12