Javascript Regex Prototype

Why does the Chrome console display /(?:)/ For the RegExp prototype?

 console.log(RegExp.prototype); console.log(/a/.__proto__); 

Is this a specific implementation? IE displays // .

This is just a matter of curiosity. I tried to see all prototypes of regular expression methods in javascript when I came across this. Of course, I found other ways to search for these methods, but this makes me wonder why this result is displayed.

I hope this question has not been asked before - I did not find anything in Stackoverflow. Thanks!

+4
source share
1 answer

Corresponding section from the specification

The RegExp prototype object itself is a regular expression object; his [[Class]] is "RegExp". The initial values ​​of the RegExp prototype of the property of these objects (15.10.7) are set as if the object was created by the expression new RegExp (), where RegExp is the standard built-in constructor with this name.

Then we move on to the new RegExp() section , which is similar to calling with an empty string. So now we have an empty regex object as a prototype.

The string representation is defined as :

Returns the String value formed by combining the strings "/", the String value of the source property of this RegExp object and "/"; plus β€œg” if the global property is true, β€œi” if the ignoreCase property is true, and β€œm” if the multi-sheeted property is true.

NOTE The returned string is of the form RegularExpressionLiteral which evaluates another RegExp object with the same behavior as this object.

Ultimately, it comes down to the property .source (explained in the new RegExp section ), which is determined by the implementation, as long as he behaves when used as a regular expression:

Let S be a String in the form of a pattern equivalent to P, in which some characters are discarded, as described below. S may or may not be identical to P or pattern; however, the internal procedure, which is the result of evaluating S as a template, should behave identically with the internal procedure defined by the constructed [[Match]] internal property.

Since new RegExp("(?:)") and new RegExp("") behave the same way, both chrome and IE follow the specification correctly. The specification even mentions this particular situation as an example:

If P is an empty string, this specification can be satisfied if S be allowed "(? :)"

The Chrome method can be considered β€œbetter” because it works as a regular expression literal: /(?:)/ Is a valid regular expression literal, while // runs a single-line comment.

+6
source

Source: https://habr.com/ru/post/1497789/


All Articles