NeilFraser / JS-Interpreter

A sandboxed JavaScript interpreter in JavaScript.
Apache License 2.0
1.98k stars 353 forks source link

RegExp constructor behaviour not spec-compliant #211

Closed cpcallen closed 3 years ago

cpcallen commented 3 years ago

There are a few ways in which the RegExp constructor's behaviour diverges from the spec (and V8):

var re = /foo/;
alert(re === RegExp(re));  // Should be true.
alert(re === new RegExp(re));  // OK.

alert(new RegExp(undefined).source);  // OK.
alert(new RegExp(null).source);  // Should be 'null'.
alert(new RegExp(true).source);  // OK.
alert(new RegExp(false).source);  // Should be 'false'.
alert(new RegExp('').source);  // OK.
alert(new RegExp('foo').source);  // OK.
alert(new RegExp('0').source);  // OK.
alert(new RegExp({}).source);  // OK.
alert(new RegExp([]).source);  // OK.
NeilFraser commented 3 years ago

Strange that it's inconsistent in JavaScript:

var re = /foo/;
alert(re === RegExp(re));   // true
var str = new String('hello');
alert(str === String(str));  // false
cpcallen commented 3 years ago

Strange that it's inconsistent in JavaScript:


var re = /foo/;
alert(re === RegExp(re));   // true

But re !== new RegExp(re).

I agree it's kind of warty, but it sort of makes sense if you think of RegExp(r) and String(s) as casts to RegExp and string (not String, unfortunately), respectively, such that if r is already a RegExp then there is nothing to do—whereas new RegExp(r) and new String(s) give you a new object of the corresponding type.

cpcallen commented 3 years ago

(There's no excuse for Date(d), though. That's just wrong no matter how you look at it.)