views:

115

answers:

2

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?

+2  A: 

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

S.Mark
Technically `null` is not an object, it's a primitive value, this misconception has been there for years, unfortunately even the `typeof` operator is wrong, since `typeof null == 'object'` which is completely incorrect. Sadly, this was too late to be fixed in the ECMAScript 5th Edition. http://wiki.ecmascript.org/doku.php?id=proposals:typeof
CMS
Thanks @CMS for the informations. +1ed to yours.
S.Mark
Thanks, now I understand why null is converted to 'null'.
Lauri Oherd
+5  A: 

It's not a bug, but you are right, null coerces to 'null' and that behavior is defined on the spec:

  1. RegExp.prototype.test(string), internally is equivalent to the expression: RegExp.prototype.exec(string) != null
  2. The exec method type converts the first argument to string, using the ToString internal operation (look the Step 1 of the exec method).
  3. The 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"]
CMS