RegExp gives unexpected result when tested against `undefined`

a 夏天 提交于 2021-02-05 06:42:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!