Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex: null is lower case letter? [duplicate]

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.

like image 288
gefei Avatar asked Feb 12 '15 14:02

gefei


2 Answers

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.

like image 78
Stephan Bijzitter Avatar answered Oct 13 '22 23:10

Stephan Bijzitter


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)

  1. Let R be this RegExp object.
  2. 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]/.

like image 29
apsillers Avatar answered Oct 14 '22 00:10

apsillers