Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are /regex/ Literals always RegExp Objects?

Tags:

javascript

Basically, my question is about how Javascript handles regex literals.

Contrasting with number, string and boolean where literals are primitive data types and corresponding Number, String and Boolean objects exist with seamless type conversion, are regex literals anonymous instances of the RegExp object or is this a case of regex being treated like primitive data with seamless type conversion to RegExp?

"The complete Reference Javascript, 2nd edition, Powell and Schneider (MH)" contradicts itself - at one place the authors say that /regex/ is automatically typecasted into RegExp when needed and at another place they say that /regex/ is nothing but an instance of RegExp!

EDIT: Please provide a reference to a reliable source

like image 731
KJ Saxena Avatar asked Aug 25 '09 06:08

KJ Saxena


1 Answers

Here's what the spec has to say:

A regular expression literal is an input element that is converted to a RegExp object when it is scanned. The object is created before evaluation of the containing program or function begins. Evaluation of the literal produces a reference to that object; it does not create a new object. Two regular expression literals in a program evaluate to regular expression objects that never compare as === to each other even if the two literals' contents are identical.

There is no primitive regex type that autoboxes to an object in the same way as string or number.

Note, however, that not all browsers implement the "instantiate-once-per-literal" behavior, including Safari and IE6 (and possibly later), so portable code shouldn't depend on it. The abortive ECMAScript 4 draft would have changed the behavior to match those browsers:

In ES3 a regular expression literal like /a*b/mg denotes a single unique RegExp object that is created the first time the literal is encountered during evaluation. In ES4 a new RegExp object is created every time the literal is encountered during evaluation.

Also, some browsers (Firefox <3, Safari) report typeof /regex/ as "function", so portable code should avoid typeof on RegExp instances—stick with instanceof.

like image 66
Miles Avatar answered Oct 24 '22 22:10

Miles