Both in Actionscript3 and Javascript these statements give the same result:
/\S/.test(null) => true
/null/.test(null) => true
/m/.test(null) => false
/n/.test(null) => true
Seems that null value is converted into string "null" in this case.
Is this a known bug in Ecmascript or am I missing something?
It's not a bug, but you are right, null
coerces to 'null'
and that behavior is defined on the spec:
RegExp.prototype.test(string)
, internally is equivalent to the expression: RegExp.prototype.exec(string) != null
exec
method type converts the first argument to string, using the ToString
internal operation (look the Step 1 of the exec
method).ToString
internal operation, explicitly returns "null"
when the input is of
type Null
.In conclusion, in your examples, the RegExp matchs against the string 'null'
, so the first non-space character, in this case the letter 'n'
.
var a = null+''; // 'null'
/\S/.test(a); // true
(null+'').match(/\S/) // ["n"]
null
is an object, and when testing against objects (non-string), its first converted to string, then its giving you that result.
You could try with /Number/.test(Number)
or /String/.test(String)
, which would return true
too.
Probably String(null)
is being called, which is 'null'
String(Number)
will give
function Number() {
[native code]
}
and /function Number/.test(Number)
return true
too
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