问题
I'm building a password strength validator that check whether password contains lower-case and upper-case characters. I use regular expressions for that and get unexpected results when provided password string is undefined - see screenshot below. I would expect both checks to return false, yet the first one returns true.
Why does the first check return true?
回答1:
Javascript will attempt to convert the argument of test to a string if it's not one. So since:
String(undefined) === "undefined"
Your first regex is true since "undefined" contains one or more lowercase letters. The second is false since there are no uppercase letters.
You can even verify this by noting that
/^undefined$/.test()
returns true.
来源:https://stackoverflow.com/questions/49578447/regexp-gives-unexpected-result-when-tested-against-undefined