Javascript Regex prototype

后端 未结 1 1115
醉梦人生
醉梦人生 2021-01-19 13:03

Why is Chrome\'s console displaying /(?:)/ for the RegExp\'s prototype?

console.log(RegExp.prototype);
console.log(/a/.__proto__);
相关标签:
1条回答
  • 2021-01-19 13:34

    Relevant section from spec

    The RegExp prototype object is itself a regular expression object; its [[Class]] is "RegExp". The initial values of the RegExp prototype object’s data properties (15.10.7) are set as if the object was created by the expression new RegExp() where RegExp is that standard built-in constructor with that name.

    Then we go to new RegExp() section, which is same as calling it with the empty string. So now we have empty regex object as the prototype.

    The string representation is defined to be:

    Return the String value formed by concatenating 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 multiline property is true.

    NOTE The returned String has the form of a RegularExpressionLiteral that evaluates to another RegExp object with the same behaviour as this object.

    It ultimately comes down to .source property (explained in the new RegExp section), which is implementation defined as long as it behaves the same when used as regex:

    Let S be a String in the form of a Pattern equivalent to P, in which certain characters are escaped as described below. S may or may not be identical to P or pattern; however, the internal procedure that would result from evaluating S as a Pattern must behave identically to the internal procedure given by the constructed object's [[Match]] internal property.

    Since new RegExp("(?:)") and new RegExp("") behave identically, both chrome and IE are following the spec correctly. The spec even mentions this specific situation as an example:

    If P is the empty String, this specification can be met by letting S be "(?:)"

    Chrome's way can be considered "better" since it appears to work as regexp literal as well: /(?:)/ is a valid regex literal whereas // starts a one-line comment.

    0 讨论(0)
提交回复
热议问题