简体   繁体   中英

JavaScript regular expression to negate an exact string match

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$" ...>

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$).*">

你可以使用这个正则表达式:

\bfooo\b

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

if (!yourString.match(/^foo$/)) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM