Can anyone explain why /[a-z]/.test(null)
returns true
while /[A-Z]/.test(null)
returns false
? Is null
(or undefined
or false
) considered a lower case letter in Javascript? Thanks.
Tested on Chrome and Firefox.
When you test anything but a String, it is turned into a String. null
is turned into a string 'null'
. Try it: console.log(new String(null));
Likewise for undefined
.
Per ECMAScript 5's section 15.10.6.3, test
is largely a wrapper for exec
, which is in section 15.10.6.2:
RegExp.prototype.exec(string)
- Let R be this RegExp object.
- Let S be the value of ToString(string).
...
Thus, we see that the argument to test
(when passed through to exec
) is coerced via the ToString
operation. When we look at ToString in section 9.8 we see the conversion table:
The abstract operation ToString converts its argument to a value of type String according to Table 13:
Table 13 — ToString Conversions
Argument Type Result Undefined | "undefined" Null | "null" ...
Null values stringify to the string "null"
, which has lowercase characters that match /[a-z]/
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With