Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bug in Ecmascript - /\S/.test(null) returns true?

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?

like image 620
Lauri Oherd Avatar asked Mar 12 '10 04:03

Lauri Oherd


2 Answers

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"]
like image 118
Christian C. Salvadó Avatar answered Nov 01 '22 05:11

Christian C. Salvadó


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

like image 31
YOU Avatar answered Nov 01 '22 05:11

YOU