/^[a-z]/.test("abc"); // <-- returns true as expected /^[a-z]/.test(null); // <-- returns true, but why?
I was assuming that the last case was going to return
false since it does not meet the regex (the value is null and thus, do no start with a character in the range). So, can anyone explain me why this is not the case?
If I do the same test in C#:
var regex = new Regex("^[a-z]"); var res = regex.IsMatch(null); // <-- ArgumentNullException
... I get an
I have tried searching for an explanation, but without any luck.
test converts its argument :
null is converted to the
You can check that in the console :
null is getting typecasted to
String form which is
"null" matches your provided regex which is why it is evaluating to
Object which has
ToString method which will be automatically called upon internally in case there is a need for a typecast.
©2020 All rights reserved.