页面模式偏好

22 文本处理

22.1 String 对象

22.1.1 String 构造函数

String 构造函数:

  • 是 %String%。
  • 是全局对象的 "String" 属性的初始值。
  • 作为构造函数调用时,创建并初始化新的 String 对象。
  • 作为函数而不是构造函数调用时执行类型转换。
  • 可以用作类定义的 extends 子句的值。希望继承指定 String 行为的子类构造函数必须包含对 String 构造函数的 super 调用,以创建并初始化具有 [[StringData]] 内部槽的子类实例。

22.1.1.1 String ( value )

调用时,此函数执行以下步骤:

  1. 如果不存在 value,则
    1. 令 string 为空 String。
  2. 否则,
    1. 如果 NewTarget 是 undefined 且 value 是 Symbol,则返回 SymbolDescriptiveString(value)。
    2. 令 string 为 ? ToString(value)。
  3. 如果 NewTarget 是 undefined,则返回 string。
  4. 返回 StringCreate(string, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%"))。

22.1.2 String 构造函数的属性

String 构造函数:

22.1.2.1 String.fromCharCode ( ...codeUnits )

可以使用任意数量的参数调用此函数,这些参数构成剩余参数 codeUnits。

调用时,它执行以下步骤:

  1. 令 result 为空 String。
  2. 对 codeUnits 的每个元素 next,执行
    1. 令 nextCU 为数值等于 ℝ(? ToUint16(next)) 的码元。
    2. 将 result 设置为 result 和 nextCU 的字符串连接。
  3. 返回 result。

此函数的 "length" 属性是 1𝔽。

22.1.2.2 String.fromCodePoint ( ...codePoints )

可以使用任意数量的参数调用此函数,这些参数构成剩余参数 codePoints。

调用时,它执行以下步骤:

  1. 令 result 为空 String。
  2. 对 codePoints 的每个元素 next,执行
    1. 令 nextCP 为 ? ToNumber(next)。
    2. 如果 nextCP 不是整数 Number,则抛出 RangeError 异常。
    3. 如果 ℝ(nextCP) < 0 或 ℝ(nextCP) > 0x10FFFF,则抛出 RangeError 异常。
    4. 将 result 设置为 result 和 UTF16EncodeCodePoint(ℝ(nextCP)) 的字符串连接。
  3. 断言:如果 codePoints 为空,则 result 为空 String。
  4. 返回 result。

此函数的 "length" 属性是 1𝔽。

22.1.2.3 String.prototype

String.prototype 的初始值是 String 原型对象。

此属性具有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }。

22.1.2.4 String.raw ( template, ...substitutions )

可以使用可变数量的参数调用此函数。第一个参数是 template,其余参数构成 List substitutions。

调用时,它执行以下步骤:

  1. 令 substitutionCount 为 substitutions 中的元素数量。
  2. 令 cooked 为 ? ToObject(template)。
  3. 令 literals 为 ? ToObject(? Get(cooked, "raw")).
  4. 令 literalCount 为 ? LengthOfArrayLike(literals)。
  5. 如果 literalCount ≤ 0,则返回空 String。
  6. 令 result 为空 String。
  7. 令 nextIndex 为 0。
  8. 重复执行,
    1. 令 nextLiteralValue 为 ? Get(literals, ! ToString(𝔽(nextIndex)))。
    2. 令 nextLiteral 为 ? ToString(nextLiteralValue)。
    3. 将 result 设置为 result 和 nextLiteral 的字符串连接。
    4. 如果 nextIndex + 1 = literalCount,则返回 result。
    5. 如果 nextIndex < substitutionCount,则
      1. 令 nextSubValue 为 substitutions[nextIndex]。
      2. 令 nextSub 为 ? ToString(nextSubValue)。
      3. 将 result 设置为 result 和 nextSub 的字符串连接。
    6. 将 nextIndex 设置为 nextIndex + 1。
注

此函数旨在用作带标签模板(13.3.11)的标签函数。以这种方式调用时,第一个参数将是格式良好的模板对象,而剩余参数将包含替换值。

22.1.3 String 原型对象的属性

String 原型对象:

  • 是 %String.prototype%。
  • 是 String 异质对象,并具有为此类对象规定的内部方法。
  • 具有 [[StringData]] 内部槽,其值为空 String。
  • 具有 "length" 属性,其初始值为 +0𝔽,并具有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }。
  • 具有 [[Prototype]] 内部槽,其值是 %Object.prototype%。

除非另有明确说明,下面定义的 String 原型对象的方法不是通用方法,传递给它们的 this value 必须是 String 值,或者是具有已初始化为 String 值的 [[StringData]] 内部槽的对象。

22.1.3.1 String.prototype.at ( index )

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 length 为 string 的长度。
  5. 令 k 为 ? ToAbsoluteIndex(index, length)。
  6. 如果 k < 0 或 k ≥ length,则返回 undefined。
  7. 返回 string 从 k 到 k + 1 的子字符串。

22.1.3.2 String.prototype.charAt ( position )

注 1

此方法返回一个单元素 String,其中包含将此对象转换为 String 后所得 String 值中索引 position 处的码元。如果该索引处没有元素,则结果为空 String。结果是 String 值,而不是 String 对象。

如果 pos 是整数 Number,则 x.charAt(pos) 的结果等价于 x.substring(pos, pos + 1) 的结果。

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 将 position 设置为 ? ToIntegerOrInfinity(position)。
  5. 令 size 为 string 的长度。
  6. 如果 position < 0 或 position ≥ size,则返回空 String。
  7. 返回 string 从 position 到 position + 1 的子字符串。
注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.3 String.prototype.charCodeAt ( position )

注 1

此方法返回一个 Number(小于 216 的非负整数 Number),它是将此对象转换为 String 后所得 String 中索引 position 处码元的数值。如果该索引处没有元素,则结果是 NaN。

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 将 position 设置为 ? ToIntegerOrInfinity(position)。
  5. 令 size 为 string 的长度。
  6. 如果 position < 0 或 position ≥ size,则返回 NaN。
  7. 返回 String string 中索引 position 处码元数值的 Number 值。
注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.4 String.prototype.codePointAt ( position )

注 1

此方法返回一个不大于 0x10FFFF𝔽 的非负整数 Number,它是从将此对象转换为 String 后所得 String 中索引 position 处字符串元素开始的 UTF-16 编码码点(6.1.4)的数值。如果该索引处没有元素,则结果是 undefined。如果有效的 UTF-16 代理对没有从 position 开始,则结果是 position 处的码元。

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 将 position 设置为 ? ToIntegerOrInfinity(position)。
  5. 令 size 为 string 的长度。
  6. 如果 position < 0 或 position ≥ size,则返回 undefined。
  7. 令 codePoint 为 CodePointAt(string, position)。
  8. 返回 𝔽(codePoint.[[CodePoint]])。
注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.5 String.prototype.concat ( ...args )

注 1

调用此方法时,它返回由 this value(转换为 String)的码元,后接转换为 String 的每个参数的码元所组成的 String 值。结果是 String 值,而不是 String 对象。

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 result 为 string。
  5. 对 args 的每个元素 next,执行
    1. 令 nextString 为 ? ToString(next)。
    2. 将 result 设置为 result 和 nextString 的字符串连接。
  6. 返回 result。

此方法的 "length" 属性是 1𝔽。

注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.6 String.prototype.constructor

String.prototype.constructor 的初始值是 %String%。

22.1.3.7 String.prototype.endsWith ( searchString [ , endPosition ] )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 isRegexp 为 ? IsRegExp(searchString)。
  5. 如果 isRegexp 是 true,则抛出 TypeError 异常。
  6. 将 searchString 设置为 ? ToString(searchString)。
  7. 令 length 为 string 的长度。
  8. 如果 endPosition 是 undefined,则令 end 为 length;否则令 end 为将 ? ToIntegerOrInfinity(endPosition) 限制在 0 和 length 之间的结果。
  9. 令 searchLength 为 searchString 的长度。
  10. 如果 searchLength = 0,则返回 true。
  11. 令 start 为 end - searchLength。
  12. 如果 start < 0,则返回 false。
  13. 令 substring 为 string 从 start 到 end 的子字符串。
  14. 如果 substring 是 searchString,则返回 true。
  15. 返回 false。
注 1

规定当第一个参数是 RegExp 时抛出异常,是为了允许未来版本定义允许此类参数值的扩展。

注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.8 String.prototype.includes ( searchString [ , position ] )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 isRegexp 为 ? IsRegExp(searchString)。
  5. 如果 isRegexp 是 true,则抛出 TypeError 异常。
  6. 将 searchString 设置为 ? ToString(searchString)。
  7. 令 length 为 string 的长度。
  8. 令 start 为将 ? ToIntegerOrInfinity(position) 限制在 0 和 length 之间的结果。
  9. 断言:如果 position 是 undefined,则 start 为 0。
  10. 令 index 为 StringIndexOf(string, searchString, start)。
  11. 如果 index 是 not-found,则返回 false。
  12. 返回 true。
注 1

如果 searchString 作为将此对象转换为 String 所得结果的子字符串,出现在一个或多个大于或等于 position 的索引处,则此函数返回 true;否则返回 false。如果 position 是 undefined,则假定为 0,从而搜索整个 String。

注 2

规定当第一个参数是 RegExp 时抛出异常,是为了允许未来版本定义允许此类参数值的扩展。

注 3

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.9 String.prototype.indexOf ( searchString [ , position ] )

注 1

如果 searchString 作为将此对象转换为 String 所得结果的子字符串,出现在一个或多个大于或等于 position 的索引处,则返回其中最小的索引;否则返回 -1𝔽。如果 position 是 undefined,则假定为 +0𝔽,从而搜索整个 String。

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 将 searchString 设置为 ? ToString(searchString)。
  5. 令 length 为 string 的长度。
  6. 令 start 为将 ? ToIntegerOrInfinity(position) 限制在 0 和 length 之间的结果。
  7. 断言:如果 position 是 undefined,则 start 为 0。
  8. 令 result 为 StringIndexOf(string, searchString, start)。
  9. 如果 result 是 not-found,则返回 -1𝔽。
  10. 返回 𝔽(result)。
注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.10 String.prototype.isWellFormed ( )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 返回 IsStringWellFormedUnicode(string)。

22.1.3.11 String.prototype.lastIndexOf ( searchString [ , position ] )

注 1

如果 searchString 作为将此对象转换为 String 所得结果的子字符串,出现在一个或多个小于或等于 position 的索引处,则返回其中最大的索引;否则返回 -1𝔽。如果 position 是 undefined,则假定为 String 值的长度,从而搜索整个 String。

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 将 searchString 设置为 ? ToString(searchString)。
  5. 令 numberPosition 为 ? ToNumber(position)。
  6. 令 length 为 string 的长度。
  7. 令 searchLength 为 searchString 的长度。
  8. 令 maxStart 为 length - searchLength。
  9. 如果 maxStart < 0,则返回 -1𝔽。
  10. 如果 numberPosition 是 NaN,则令 start 为 maxStart;否则令 start 为将 ! ToIntegerOrInfinity(numberPosition) 限制在 0 和 maxStart 之间的结果。
  11. 断言:如果 position 是 undefined,则 start 是 maxStart。
  12. 令 result 为 StringLastIndexOf(string, searchString, start)。
  13. 如果 result 是 not-found,则返回 -1𝔽。
  14. 返回 𝔽(result)。
注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.12 String.prototype.localeCompare ( that [ , reserved1 [ , reserved2 ] ] )

包含 ECMA-402 国际化 API 的 ECMAScript 实现必须按照 ECMA-402 的规定实现此方法。否则,使用以下此方法的规范:

此方法返回一个不是 NaN 的 Number,用于表示 this value(转换为 String string)与 that(转换为 String thatValue)之间由实现定义、对区域设置敏感的 String 比较结果。结果旨在对应根据宿主环境当前区域设置惯例对 String 值进行的排序顺序;当 string 排在 thatValue 之前时结果为负,当 string 排在 thatValue 之后时结果为正,在其他所有情况下结果为零(表示 string 与 thatValue 之间没有相对排序)。

执行比较之前,此方法执行以下步骤来准备 Strings:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 thatValue 为 ? ToString(that)。

此方法第二个和第三个可选参数的含义定义于 ECMA-402;不包含 ECMA-402 支持的实现不得为这些参数位置赋予任何其他解释。

实际返回值由实现定义,以允许在其中编码其他信息;但将此方法视为接受两个参数的方法时,要求它是一个一致的比较器,在所有 String 的集合上定义全序。还要求此方法识别并遵守 Unicode 标准中的规范等价,包括在比较可区分但规范等价的 Strings 时返回 +0𝔽。

注 1

此方法本身并不直接适合作为 Array.prototype.sort 的参数,因为后者要求一个接受两个参数的函数。

注 2

此方法可以依赖 ECMAScript 环境从宿主环境获得的任何语言和/或区域设置敏感比较功能,并旨在按照宿主环境当前区域设置的惯例进行比较。不过,无论比较能力如何,此方法都必须按照 Unicode 标准识别并遵守规范等价——例如,以下比较都必须返回 +0𝔽:

// Å ANGSTROM SIGN 与
// Å LATIN CAPITAL LETTER A + COMBINING RING ABOVE
"\u212B".localeCompare("A\u030A")

// Ω OHM SIGN 与
// Ω GREEK CAPITAL LETTER OMEGA
"\u2126".localeCompare("\u03A9")

// ṩ LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE 与
// ṩ LATIN SMALL LETTER S + COMBINING DOT ABOVE + COMBINING DOT BELOW
"\u1E69".localeCompare("s\u0307\u0323")

// ḍ̇ LATIN SMALL LETTER D WITH DOT ABOVE + COMBINING DOT BELOW 与
// ḍ̇ LATIN SMALL LETTER D WITH DOT BELOW + COMBINING DOT ABOVE
"\u1E0B\u0323".localeCompare("\u1E0D\u0307")

// 가 HANGUL CHOSEONG KIYEOK + HANGUL JUNGSEONG A 与
// 가 HANGUL SYLLABLE GA
"\u1100\u1161".localeCompare("\uAC00")

有关规范等价的定义和讨论,请参见 Unicode 标准第 2 章和第 3 章,以及 Unicode Standard Annex #15, Unicode Normalization Forms 和 Unicode Technical Note #5, Canonical Equivalence in Applications。另请参见 Unicode Technical Standard #10, Unicode Collation Algorithm。

建议此方法不遵守 Unicode 标准第 3 章第 3.7 节所定义的 Unicode 兼容等价或兼容分解。

注 3

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.13 String.prototype.match ( regexpOrPattern )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 如果 regexpOrPattern 是 Object,则
    1. 令 matcher 为 ? GetMethod(regexpOrPattern, %Symbol.match%)。
    2. 如果 matcher 不是 undefined,则
      1. 返回 ? Call(matcher, regexpOrPattern, « thisValue »)。
  4. 令 string 为 ? ToString(thisValue)。
  5. 令 regexp 为 ? RegExpCreate(regexpOrPattern, undefined)。
  6. 返回 ? Invoke(regexp, %Symbol.match%, « string »)。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.14 String.prototype.matchAll ( regexpOrPattern )

此方法使用 regexpOrPattern 对表示 this value 的 String 执行正则表达式匹配,并返回一个生成匹配结果的迭代器。每个匹配结果都是一个 Array,第一个元素是 String 中匹配的部分,后续元素是任何捕获组所匹配的部分。如果正则表达式从未匹配,则返回的迭代器不会生成任何匹配结果。

调用时,它执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 如果 regexpOrPattern 是 Object,则
    1. 令 isRegexp 为 ? IsRegExp(regexpOrPattern)。
    2. 如果 isRegexp 是 true,则
      1. 令 flags 为 ? Get(regexpOrPattern, "flags")。
      2. 执行 ? RequireObjectCoercible(flags)。
      3. 如果 ? ToString(flags) 不包含 "g",则抛出 TypeError 异常。
    3. 令 matcher 为 ? GetMethod(regexpOrPattern, %Symbol.matchAll%)。
    4. 如果 matcher 不是 undefined,则
      1. 返回 ? Call(matcher, regexpOrPattern, « thisValue »)。
  4. 令 string 为 ? ToString(thisValue)。
  5. 令 regexp 为 ? RegExpCreate(regexpOrPattern, "g")。
  6. 返回 ? Invoke(regexp, %Symbol.matchAll%, « string »)。
注 1
此方法有意设计为通用方法,它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。
注 2
与 String.prototype.split 类似,String.prototype.matchAll 被设计为通常不会修改其输入。

22.1.3.15 String.prototype.normalize ( [ form ] )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 如果 form 是 undefined,则将 form 设置为 "NFC"。
  5. 否则,将 form 设置为 ? ToString(form)。
  6. 如果 form 不是 "NFC"、"NFD"、"NFKC" 或 "NFKD" 之一,则抛出 RangeError 异常。
  7. 令 normal 为按照最新 Unicode 标准,Normalization Forms 中的规定,将 string 规范化为由 form 命名的规范化形式所得的 String 值。
  8. 返回 normal。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.16 String.prototype.padEnd ( maxLength [ , fillString ] )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 返回 ? StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, end)。

22.1.3.17 String.prototype.padStart ( maxLength [ , fillString ] )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 返回 ? StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, start)。

22.1.3.17.1 StringPaddingBuiltinsImpl ( thisValue, maxLength, fillString, placement )

抽象操作 StringPaddingBuiltinsImpl,接收参数 thisValue (ECMAScript 语言值)、maxLength (ECMAScript 语言值)、fillString (ECMAScript 语言值) 和 placement ((start 或 end));返回值:(正常完成 (值:String) 或 抛出完成)。 调用时执行以下步骤:

  1. 令 string 为 ? ToString(thisValue)。
  2. 令 intMaxLength 为 ℝ(? ToLength(maxLength))。
  3. 令 stringLength 为 string 的长度。
  4. 如果 intMaxLength ≤ stringLength,则返回 string。
  5. 如果 fillString 是 undefined,则将 fillString 设置为仅由码元 0x0020 (SPACE) 组成的 String 值。
  6. 否则,将 fillString 设置为 ? ToString(fillString)。
  7. 返回 StringPad(string, intMaxLength, fillString, placement)。

22.1.3.17.2 StringPad ( string, maxLength, fillString, placement )

抽象操作 StringPad,接收参数 string (String)、maxLength (非负整数)、fillString (String) 和 placement ((start 或 end));返回值:String。 调用时执行以下步骤:

  1. 令 stringLength 为 string 的长度。
  2. 如果 maxLength ≤ stringLength,则返回 string。
  3. 如果 fillString 是空 String,则返回 string。
  4. 令 fillLength 为 maxLength - stringLength。
  5. 令 truncatedStringFiller 为由 fillString 的重复连接组成并截断到长度 fillLength 的 String 值。
  6. 如果 placement 是 start,则返回 truncatedStringFiller 和 string 的字符串连接。
  7. 返回 string 和 truncatedStringFiller 的字符串连接。
注 1

参数 maxLength 将被限制,使其不能小于 string 的长度。

注 2

参数 fillString 默认为 " "(由码元 0x0020 SPACE 组成的 String 值)。

22.1.3.17.3 ToZeroPaddedDecimalString ( n, minLength )

抽象操作 ToZeroPaddedDecimalString,接收参数 n (非负整数) 和 minLength (非负整数);返回值:String。 调用时执行以下步骤:

  1. 令 string 为 n 的 String 表示,并格式化为十进制数。
  2. 返回 StringPad(string, minLength, "0", start)。

22.1.3.18 String.prototype.repeat ( count )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 n 为 ? ToIntegerOrInfinity(count)。
  5. 如果 n < 0 或 n = +∞,则抛出 RangeError 异常。
  6. 如果 n = 0,则返回空 String。
  7. 返回由 n 份 string 依次追加组成的 String 值。
注 1

此方法创建由 this value(转换为 String)的码元重复 count 次组成的 String 值。

注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.19 String.prototype.replace ( searchValue, replaceValue )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 如果 searchValue 是 Object,则
    1. 令 replacer 为 ? GetMethod(searchValue, %Symbol.replace%)。
    2. 如果 replacer 不是 undefined,则
      1. 返回 ? Call(replacer, searchValue, « thisValue, replaceValue »)。
  4. 令 string 为 ? ToString(thisValue)。
  5. 令 searchString 为 ? ToString(searchValue)。
  6. 令 functionalReplace 为 IsCallable(replaceValue)。
  7. 如果 functionalReplace 是 false,则
    1. 将 replaceValue 设置为 ? ToString(replaceValue)。
  8. 令 searchLength 为 searchString 的长度。
  9. 令 position 为 StringIndexOf(string, searchString, 0)。
  10. 如果 position 是 not-found,则返回 string。
  11. 令 preceding 为 string 从 0 到 position 的子字符串。
  12. 令 following 为 string 从 position + searchLength 开始的子字符串。
  13. 如果 functionalReplace 是 true,则
    1. 令 replacement 为 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(position), string »))。
  14. 否则,
    1. 断言:replaceValue 是 String。
    2. 令 captures 为新的空 List。
    3. 令 replacement 为 ! GetSubstitution(searchString, string, position, captures, undefined, replaceValue)。
  15. 返回 preceding、replacement 和 following 的字符串连接。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.19.1 GetSubstitution ( matched, string, position, captures, namedCaptures, replacementTemplate )

抽象操作 GetSubstitution,接收参数 matched (String)、string (String)、position (非负整数)、captures (列表 (元素:(String 或 undefined)))、namedCaptures ((Object 或 undefined)) 和 replacementTemplate (String);返回值:(正常完成 (值:String) 或 抛出完成)。 就此抽象操作而言,十进制数字是从 0x0030 (DIGIT ZERO) 到 0x0039 (DIGIT NINE) 闭区间内的码元。 调用时执行以下步骤:

  1. 令 stringLength 为 string 的长度。
  2. 断言:position ≤ stringLength。
  3. 令 result 为空 String。
  4. 令 templateRemainder 为 replacementTemplate。
  5. 当 templateRemainder 不是空 String 时,重复执行,
    1. 注:以下步骤会分离出 ref(templateRemainder 的一个前缀),确定 refReplacement(其替换值),然后将该替换值追加到 result。
    2. 如果 templateRemainder 以 "$$" 开头,则
      1. 令 ref 为 "$$"。
      2. 令 refReplacement 为 "$"。
    3. 否则如果 templateRemainder 以 "$`" 开头,则
      1. 令 ref 为 "$`"。
      2. 令 refReplacement 为 string 从 0 到 position 的子字符串。
    4. 否则如果 templateRemainder 以 "$&" 开头,则
      1. 令 ref 为 "$&"。
      2. 令 refReplacement 为 matched。
    5. 否则如果 templateRemainder 以 "$'"(0x0024 (DOLLAR SIGN) 后跟 0x0027 (APOSTROPHE))开头,则
      1. 令 ref 为 "$'"。
      2. 令 matchLength 为 matched 的长度。
      3. 令 tailPosition 为 position + matchLength。
      4. 令 refReplacement 为 string 从 min(tailPosition, stringLength) 开始的子字符串。
      5. 注:只有当此抽象操作由对某对象调用 %RegExp.prototype% 的内在 %Symbol.replace% 方法,而该对象的 "exec" 属性不是内在 %RegExp.prototype.exec% 时,tailPosition 才可能超过 stringLength。
    6. 否则如果 templateRemainder 以 "$" 后跟 1 个或多个十进制数字开头,则
      1. 如果 templateRemainder 以 "$" 后跟 2 个或更多十进制数字开头,则令 digitCount 为 2;否则令 digitCount 为 1。
      2. 令 digits 为 templateRemainder 从 1 到 1 + digitCount 的子字符串。
      3. 令 index 为 ℝ(StringToNumber(digits))。
      4. 断言:0 ≤ index ≤ 99。
      5. 令 captureLength 为 captures 中的元素数量。
      6. 如果 index > captureLength 且 digitCount = 2,则
        1. 注:当两位替换模式指定的索引超过捕获组数量时,它会被视为一位替换模式,后跟一个字面数字。
        2. 将 digitCount 设置为 1。
        3. 将 digits 设置为 digits 从 0 到 1 的子字符串。
        4. 将 index 设置为 ℝ(StringToNumber(digits))。
      7. 令 ref 为 templateRemainder 从 0 到 1 + digitCount 的子字符串。
      8. 如果 1 ≤ index ≤ captureLength,则
        1. 令 capture 为 captures[index - 1]。
        2. 如果 capture 是 undefined,则
          1. 令 refReplacement 为空 String。
        3. 否则,
          1. 令 refReplacement 为 capture。
      9. 否则,
        1. 令 refReplacement 为 ref。
    7. 否则如果 templateRemainder 以 "$<" 开头,则
      1. 令 gtPosition 为 StringIndexOf(templateRemainder, ">", 0)。
      2. 如果 gtPosition 是 not-found 或 namedCaptures 是 undefined,则
        1. 令 ref 为 "$<"。
        2. 令 refReplacement 为 ref。
      3. 否则,
        1. 令 ref 为 templateRemainder 从 0 到 gtPosition + 1 的子字符串。
        2. 令 groupName 为 templateRemainder 从 2 到 gtPosition 的子字符串。
        3. 断言:namedCaptures 是 Object。
        4. 令 capture 为 ? Get(namedCaptures, groupName)。
        5. 如果 capture 是 undefined,则
          1. 令 refReplacement 为空 String。
        6. 否则,
          1. 令 refReplacement 为 ? ToString(capture)。
    8. 否则,
      1. 令 ref 为 templateRemainder 从 0 到 1 的子字符串。
      2. 令 refReplacement 为 ref。
    9. 令 refLength 为 ref 的长度。
    10. 将 templateRemainder 设置为 templateRemainder 从 refLength 开始的子字符串。
    11. 将 result 设置为 result 和 refReplacement 的字符串连接。
  6. 返回 result。

22.1.3.20 String.prototype.replaceAll ( searchValue, replaceValue )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 如果 searchValue 是 Object,则
    1. 令 isRegexp 为 ? IsRegExp(searchValue)。
    2. 如果 isRegexp 是 true,则
      1. 令 flags 为 ? Get(searchValue, "flags")。
      2. 执行 ? RequireObjectCoercible(flags)。
      3. 如果 ? ToString(flags) 不包含 "g",则抛出 TypeError 异常。
    3. 令 replacer 为 ? GetMethod(searchValue, %Symbol.replace%)。
    4. 如果 replacer 不是 undefined,则
      1. 返回 ? Call(replacer, searchValue, « thisValue, replaceValue »)。
  4. 令 string 为 ? ToString(thisValue)。
  5. 令 searchString 为 ? ToString(searchValue)。
  6. 令 functionalReplace 为 IsCallable(replaceValue)。
  7. 如果 functionalReplace 是 false,则
    1. 将 replaceValue 设置为 ? ToString(replaceValue)。
  8. 令 searchLength 为 searchString 的长度。
  9. 令 advanceBy 为 max(1, searchLength)。
  10. 令 matchPositions 为新的空 List。
  11. 令 position 为 StringIndexOf(string, searchString, 0)。
  12. 当 position 不是 not-found 时,重复执行,
    1. 将 position 追加到 matchPositions。
    2. 将 position 设置为 StringIndexOf(string, searchString, position + advanceBy)。
  13. 令 endOfLastMatch 为 0。
  14. 令 result 为空 String。
  15. 对 matchPositions 的每个元素 matchPosition,执行
    1. 令 preserved 为 string 从 endOfLastMatch 到 matchPosition 的子字符串。
    2. 如果 functionalReplace 是 true,则
      1. 令 replacement 为 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(matchPosition), string »))。
    3. 否则,
      1. 断言:replaceValue 是 String。
      2. 令 captures 为新的空 List。
      3. 令 replacement 为 ! GetSubstitution(searchString, string, matchPosition, captures, undefined, replaceValue)。
    4. 将 result 设置为 result、preserved 和 replacement 的字符串连接。
    5. 将 endOfLastMatch 设置为 matchPosition + searchLength。
  16. 如果 endOfLastMatch < string 的长度,则
    1. 将 result 设置为 result 和 string 从 endOfLastMatch 开始的子字符串的字符串连接。
  17. 返回 result。

22.1.3.21 String.prototype.search ( regexpOrPattern )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 如果 regexpOrPattern 是 Object,则
    1. 令 searcher 为 ? GetMethod(regexpOrPattern, %Symbol.search%)。
    2. 如果 searcher 不是 undefined,则
      1. 返回 ? Call(searcher, regexpOrPattern, « thisValue »)。
  4. 令 string 为 ? ToString(thisValue)。
  5. 令 regexp 为 ? RegExpCreate(regexpOrPattern, undefined)。
  6. 返回 ? Invoke(regexp, %Symbol.search%, « string »)。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.22 String.prototype.slice ( start, end )

此方法返回将此对象转换为 String 所得结果的一个子字符串,从索引 start 开始,到 String 的索引 end 之前结束(如果 end 是 undefined,则一直到 String 末尾)。如果 start 为负,则将其视为 sourceLength + start,其中 sourceLength 是 String 的长度。如果 end 为负,则将其视为 sourceLength + end,其中 sourceLength 是 String 的长度。结果是 String 值,而不是 String 对象。

调用时,它执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 length 为 string 的长度。
  5. 令 from 为 ? ToClampedIndex(start, length)。
  6. 如果 end 是 undefined,则令 to 为 length;否则令 to 为 ? ToClampedIndex(end, length)。
  7. 如果 from ≥ to,则返回空 String。
  8. 返回 string 从 from 到 to 的子字符串。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.23 String.prototype.split ( separator, limit )

此方法返回一个 Array,其中存储了将此对象转换为 String 所得结果的子字符串。通过从左到右搜索 separator 的出现位置来确定这些子字符串;这些出现位置不属于返回数组中的任何 String,而是用于分割 String 值。separator 的值可以是任意长度的 String,也可以是具有 %Symbol.split% 方法的对象,例如 RegExp。

调用时,它执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 如果 separator 是 Object,则
    1. 令 splitter 为 ? GetMethod(separator, %Symbol.split%)。
    2. 如果 splitter 不是 undefined,则
      1. 返回 ? Call(splitter, separator, « thisValue, limit »)。
  4. 令 string 为 ? ToString(thisValue)。
  5. 如果 limit 是 undefined,则令 lim 为 232 - 1;否则令 lim 为 ℝ(? ToUint32(limit))。
  6. 令 separatorString 为 ? ToString(separator)。
  7. 如果 lim = 0,则
    1. 返回 CreateArrayFromList(« »)。
  8. 如果 separator 是 undefined,则
    1. 返回 CreateArrayFromList(« string »)。
  9. 令 separatorLength 为 separatorString 的长度。
  10. 如果 separatorLength = 0,则
    1. 令 stringLength 为 string 的长度。
    2. 令 outLength 为将 lim 限制在 0 和 stringLength 之间的结果。
    3. 令 head 为 string 从 0 到 outLength 的子字符串。
    4. 令 codeUnits 为由 head 的元素所组成的码元序列构成的 List。
    5. 返回 CreateArrayFromList(codeUnits)。
  11. 如果 string 是空 String,则返回 CreateArrayFromList(« string »)。
  12. 令 substrings 为新的空 List。
  13. 令 searchStart 为 0。
  14. 令 matchIndex 为 StringIndexOf(string, separatorString, 0)。
  15. 当 matchIndex 不是 not-found 时,重复执行,
    1. 令 substring 为 string 从 searchStart 到 matchIndex 的子字符串。
    2. 将 substring 追加到 substrings。
    3. 如果 substrings 中的元素数量是 lim,则返回 CreateArrayFromList(substrings)。
    4. 将 searchStart 设置为 matchIndex + separatorLength。
    5. 将 matchIndex 设置为 StringIndexOf(string, separatorString, searchStart)。
  16. 令 substring 为 string 从 searchStart 开始的子字符串。
  17. 将 substring 追加到 substrings。
  18. 返回 CreateArrayFromList(substrings)。
注 1

separator 的值可以是空 String。在这种情况下,separator 不匹配输入 String 开头或末尾的空子字符串,也不匹配上一个分隔符匹配末尾的空子字符串。如果 separator 是空 String,则 String 会被拆分为单独的码元元素;结果数组的长度等于 String 的长度,并且每个子字符串包含一个码元。

如果 this value 是空 String(或转换为后是空 String),则结果取决于 separator 是否能匹配空 String。如果可以,则结果数组不包含任何元素。否则,结果数组包含一个元素,即空 String。

如果 separator 是 undefined,则结果数组只包含一个 String,即 this value(转换为 String)。如果 limit 不是 undefined,则输出数组会被截断,使其包含的元素不超过 limit 个。

注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.24 String.prototype.startsWith ( searchString [ , position ] )

调用时,此方法执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 isRegexp 为 ? IsRegExp(searchString)。
  5. 如果 isRegexp 是 true,则抛出 TypeError 异常。
  6. 将 searchString 设置为 ? ToString(searchString)。
  7. 令 length 为 string 的长度。
  8. 令 start 为将 ? ToIntegerOrInfinity(position) 限制在 0 和 length 之间的结果。
  9. 断言:如果 position 是 undefined,则 start 为 0。
  10. 令 searchLength 为 searchString 的长度。
  11. 如果 searchLength = 0,则返回 true。
  12. 令 end 为 start + searchLength。
  13. 如果 end > length,则返回 false。
  14. 令 substring 为 string 从 start 到 end 的子字符串。
  15. 如果 substring 是 searchString,则返回 true。
  16. 返回 false。
注 1

规定当第一个参数是 RegExp 时抛出异常,是为了允许未来版本定义允许此类参数值的扩展。

注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.25 String.prototype.substring ( start, end )

此方法返回将此对象转换为 String 所得结果的一个子字符串,从索引 start 开始,到 String 的索引 end 之前结束(如果 end 是 undefined,则一直到 String 末尾)。结果是 String 值,而不是 String 对象。

如果任一参数是 NaN 或负数,则替换为零;如果任一参数严格大于 String 的长度,则替换为 String 的长度。

如果 start 严格大于 end,则交换它们。

调用时,它执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 length 为 string 的长度。
  5. 令 finalStart 为将 ? ToIntegerOrInfinity(start) 限制在 0 和 length 之间的结果。
  6. 断言:如果 start 是 undefined,则 finalStart 为 0。
  7. 如果 end 是 undefined,则令 finalEnd 为 length;否则令 finalEnd 为将 ? ToIntegerOrInfinity(end) 限制在 0 和 length 之间的结果。
  8. 令 from 为 min(finalStart, finalEnd)。
  9. 令 to 为 max(finalStart, finalEnd)。
  10. 返回 string 从 from 到 to 的子字符串。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.26 String.prototype.toLocaleLowerCase ( [ reserved1 [ , reserved2 ] ] )

包含 ECMA-402 国际化 API 的 ECMAScript 实现必须按照 ECMA-402 的规定实现此方法。否则,使用以下此方法的规范:

此方法按照 6.1.4 中的说明,将 String 值解释为 UTF-16 编码码点序列。

它的工作方式与 toLowerCase 完全相同,只是旨在产生符合宿主环境当前区域设置惯例的区域设置敏感结果。只有在少数情况下(例如土耳其语),当该语言的规则与常规 Unicode 大小写映射冲突时,结果才会有所不同。

此方法可选参数的含义定义于 ECMA-402;不包含 ECMA-402 支持的实现不得将这些参数位置用于其他用途。

注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.27 String.prototype.toLocaleUpperCase ( [ reserved1 [ , reserved2 ] ] )

包含 ECMA-402 国际化 API 的 ECMAScript 实现必须按照 ECMA-402 的规定实现此方法。否则,使用以下此方法的规范:

此方法按照 6.1.4 中的说明,将 String 值解释为 UTF-16 编码码点序列。

它的工作方式与 toUpperCase 完全相同,只是旨在产生符合宿主环境当前区域设置惯例的区域设置敏感结果。只有在少数情况下(例如土耳其语),当该语言的规则与常规 Unicode 大小写映射冲突时,结果才会有所不同。

此方法可选参数的含义定义于 ECMA-402;不包含 ECMA-402 支持的实现不得将这些参数位置用于其他用途。

注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.28 String.prototype.toLowerCase ( )

此方法按照 6.1.4 中的说明,将 String 值解释为 UTF-16 编码码点序列。

调用时,它执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 sText 为 StringToCodePoints(string)。
  5. 令 lowerText 为根据 Unicode Default Case Conversion 算法的 toLowercase(sText)。
  6. 令 lowercaseString 为 CodePointsToString(lowerText)。
  7. 返回 lowercaseString。

结果必须根据 Unicode Character Database 中与区域设置无关的大小写映射得出(这明确不仅包括文件 UnicodeData.txt,还包括随附文件 SpecialCasing.txt 中所有与区域设置无关的映射)。

注 1

某些码点的大小写映射可能产生多个码点。在这种情况下,结果 String 的长度可能与源 String 不同。由于 toUpperCase 和 toLowerCase 都具有上下文敏感行为,因此这些方法并不对称。换句话说,s.toUpperCase().toLowerCase() 不一定等于 s.toLowerCase()。

注 2

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.29 String.prototype.toString ( )

调用时,此方法执行以下步骤:

  1. 返回 ? ThisStringValue(this value)。
注

对于 String 对象,此方法碰巧返回与 valueOf 方法相同的内容。

22.1.3.30 String.prototype.toUpperCase ( )

此方法按照 6.1.4 中的说明,将 String 值解释为 UTF-16 编码码点序列。

它的行为与 String.prototype.toLowerCase 完全相同,只是 String 使用 Unicode Default Case Conversion 的 toUppercase 算法进行映射。

注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.31 String.prototype.toWellFormed ( )

此方法返回此对象的 String 表示,其中所有不属于代理对的前导代理项和尾随代理项都会替换为 U+FFFD (REPLACEMENT CHARACTER)。

调用时,它执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 执行 ? RequireObjectCoercible(thisValue)。
  3. 令 string 为 ? ToString(thisValue)。
  4. 令 stringLength 为 string 的长度。
  5. 令 k 为 0。
  6. 令 result 为空 String。
  7. 当 k < stringLength 时,重复执行,
    1. 令 codePoint 为 CodePointAt(string, k)。
    2. 如果 codePoint.[[IsUnpairedSurrogate]] 是 true,则
      1. 将 result 设置为 result 和 0xFFFD (REPLACEMENT CHARACTER) 的字符串连接。
    3. 否则,
      1. 将 result 设置为 result 和 UTF16EncodeCodePoint(codePoint.[[CodePoint]]) 的字符串连接。
    4. 将 k 设置为 k + codePoint.[[CodeUnitCount]]。
  8. 返回 result。

22.1.3.32 String.prototype.trim ( )

此方法按照 6.1.4 中的说明,将 String 值解释为 UTF-16 编码码点序列。

调用时,它执行以下步骤:

  1. 令 thisValue 为 this value。
  2. 返回 ? TrimString(thisValue, start+end)。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.32.1 TrimString ( arg, where )

抽象操作 TrimString,接收参数 arg (ECMAScript 语言值) 和 where ((start、end 或 start+end));返回值:(正常完成 (值:String) 或 抛出完成)。 它按照 6.1.4 中的说明,将 arg 解释为 UTF-16 编码码点序列。 调用时执行以下步骤:

  1. 执行 ? RequireObjectCoercible(arg)。
  2. 令 string 为 ? ToString(arg)。
  3. 如果 where 是 start,则
    1. 令 trimmedString 为移除 string 前导空白后的副本 String 值。
  4. 否则如果 where 是 end,则
    1. 令 trimmedString 为移除 string 尾随空白后的副本 String 值。
  5. 否则,
    1. 断言:where 是 start+end。
    2. 令 trimmedString 为同时移除 string 前导和尾随空白后的副本 String 值。
  6. 返回 trimmedString。

空白的定义是 WhiteSpace 和 LineTerminator 的并集。在确定 Unicode 码点是否属于 Unicode 通用类别“Space_Separator”(“Zs”)时,码元序列按照 6.1.4 中的规定解释为 UTF-16 编码码点序列。

22.1.3.33 String.prototype.trimEnd ( )

此方法按照 6.1.4 中的说明,将 String 值解释为 UTF-16 编码码点序列。

调用时,它执行以下步骤:

  1. 令 string 为 this value。
  2. 返回 ? TrimString(string, end)。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.34 String.prototype.trimStart ( )

此方法按照 6.1.4 中的说明,将 String 值解释为 UTF-16 编码码点序列。

调用时,它执行以下步骤:

  1. 令 string 为 this value。
  2. 返回 ? TrimString(string, start)。
注

此方法有意设计为通用方法;它不要求其 this value 是 String 对象。因此,它可以被转移到其他种类的对象上用作方法。

22.1.3.35 String.prototype.valueOf ( )

调用时,此方法执行以下步骤:

  1. 返回 ? ThisStringValue(this value)。

22.1.3.35.1 ThisStringValue ( arg )

抽象操作 ThisStringValue,接收参数 arg (ECMAScript 语言值);返回值:(正常完成 (值:String) 或 抛出完成)。 调用时执行以下步骤:

  1. 如果 arg 是 String,则返回 arg。
  2. 如果 arg 是 Object 且 arg 具有 [[StringData]] 内部槽,则
    1. 令 string 为 arg.[[StringData]]。
    2. 断言:string 是 String。
    3. 返回 string。
  3. 抛出 TypeError 异常。

22.1.3.36 String.prototype [ %Symbol.iterator% ] ( )

此方法返回一个迭代器对象,用于迭代 String 值的码点,并将每个码点作为 String 值返回。

调用时,它执行以下步骤:

  1. 令 string 为 this value。
  2. 执行 ? RequireObjectCoercible(string)。
  3. 将 string 设置为 ? ToString(string)。
  4. 令 closure 为不带参数的新 Abstract Closure,它捕获 string,并在被调用时执行以下步骤:
    1. 令 length 为 string 的长度。
    2. 令 position 为 0。
    3. 当 position < length 时,重复执行,
      1. 令 codePoint 为 CodePointAt(string, position)。
      2. 令 nextIndex 为 position + codePoint.[[CodeUnitCount]]。
      3. 令 resultString 为 string 从 position 到 nextIndex 的子字符串。
      4. 将 position 设置为 nextIndex。
      5. 执行 ? GeneratorYield(CreateIteratorResultObject(resultString, false))。
    4. 返回 NormalCompletion(unused)。
  5. 返回 CreateIteratorFromClosure(closure, "%StringIteratorPrototype%", %StringIteratorPrototype%)。

此方法的 "name" 属性值是 "[Symbol.iterator]"。

22.1.4 String 实例的属性

String 实例是 String 异质对象,并具有为此类对象规定的内部方法。String 实例从 String 原型对象继承属性。String 实例还具有 [[StringData]] 内部槽。[[StringData]] 内部槽是此 String 对象表示的 String 值。

String 实例具有 "length" 属性,以及一组名称为整数索引的可枚举属性。

22.1.4.1 length

此 String 对象所表示的 String 值中的元素数量。

一旦 String 对象初始化,此属性便不会改变。它具有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }。

22.1.5 String 迭代器对象

String Iterator 是表示对某个特定 String 实例对象进行某次特定迭代的对象。String Iterator 对象没有具名构造函数。相反,String Iterator 对象通过调用 String 实例对象的某些方法创建。

22.1.5.1 %StringIteratorPrototype% 对象

%StringIteratorPrototype% 对象:

22.1.5.1.1 %StringIteratorPrototype%.next ( )

  1. 返回 ? GeneratorResume(this value, empty, "%StringIteratorPrototype%")。

22.1.5.1.2 %StringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 属性的初始值是 String 值 "String Iterator"。

此属性具有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }。

22.2 RegExp(正则表达式)对象

RegExp 对象包含一个正则表达式及其相关标志。

注

正则表达式的形式和功能以 Perl 5 编程语言中的正则表达式机制为模型。

22.2.1 模式

RegExp 构造函数将以下文法应用于输入模式 String。如果文法无法将该 String 解释为 Pattern 的展开,则发生错误。

语法

Pattern[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Disjunction[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] | Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Alternative[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: [empty] Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Term[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Term[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Assertion[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Atom[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Atom[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Quantifier Assertion[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: ^ $ \b \B (?= Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?! Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?<= Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?<! Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) Quantifier :: QuantifierPrefix QuantifierPrefix ? QuantifierPrefix :: * + ? { DecimalDigits[~Sep] } { DecimalDigits[~Sep] ,} { DecimalDigits[~Sep] , DecimalDigits[~Sep] } Atom[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: PatternCharacter . \ AtomEscape[?UnicodeMode, ?NamedCaptureGroups] CharacterClass[?UnicodeMode, ?UnicodeSetsMode] ( GroupSpecifier[?UnicodeMode]opt Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers : Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) RegularExpressionModifiers :: [empty] RegularExpressionModifiers RegularExpressionModifier RegularExpressionModifier :: one of i m s SyntaxCharacter :: one of ^ $ \ . * + ? ( ) [ ] { } | PatternCharacter :: SourceCharacter but not SyntaxCharacter AtomEscape[UnicodeMode, NamedCaptureGroups] :: DecimalEscape CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode] [+NamedCaptureGroups] k GroupName[?UnicodeMode] CharacterEscape[UnicodeMode] :: ControlEscape c AsciiLetter 0 [lookahead ∉ DecimalDigit] HexEscapeSequence RegExpUnicodeEscapeSequence[?UnicodeMode] IdentityEscape[?UnicodeMode] ControlEscape :: one of f n r t v GroupSpecifier[UnicodeMode] :: ? GroupName[?UnicodeMode] GroupName[UnicodeMode] :: < RegExpIdentifierName[?UnicodeMode] > RegExpIdentifierName[UnicodeMode] :: RegExpIdentifierStart[?UnicodeMode] RegExpIdentifierName[?UnicodeMode] RegExpIdentifierPart[?UnicodeMode] RegExpIdentifierStart[UnicodeMode] :: IdentifierStartChar \ RegExpUnicodeEscapeSequence[+UnicodeMode] [~UnicodeMode] UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart[UnicodeMode] :: IdentifierPartChar \ RegExpUnicodeEscapeSequence[+UnicodeMode] [~UnicodeMode] UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpUnicodeEscapeSequence[UnicodeMode] :: [+UnicodeMode] u HexLeadSurrogate \u HexTrailSurrogate [+UnicodeMode] u HexLeadSurrogate [+UnicodeMode] u HexTrailSurrogate [+UnicodeMode] u HexNonSurrogate [~UnicodeMode] u Hex4Digits [+UnicodeMode] u{ CodePoint } UnicodeLeadSurrogate :: any Unicode code point in the inclusive interval from U+D800 to U+DBFF UnicodeTrailSurrogate :: any Unicode code point in the inclusive interval from U+DC00 to U+DFFF

对于每个 \u HexTrailSurrogate,如果其关联 u HexLeadSurrogate 的选择存在歧义,则应将其与最近的、否则将没有对应 \u HexTrailSurrogate 的可能 u HexLeadSurrogate 关联。

HexLeadSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xD800 to 0xDBFF HexTrailSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xDC00 to 0xDFFF HexNonSurrogate :: Hex4Digits but only if the MV of Hex4Digits is not in the inclusive interval from 0xD800 to 0xDFFF IdentityEscape[UnicodeMode] :: [+UnicodeMode] SyntaxCharacter [+UnicodeMode] / [~UnicodeMode] SourceCharacter but not UnicodeIDContinue DecimalEscape :: NonZeroDigit DecimalDigits[~Sep]opt [lookahead ∉ DecimalDigit] CharacterClassEscape[UnicodeMode] :: d D s S w W [+UnicodeMode] p{ UnicodePropertyValueExpression } [+UnicodeMode] P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue LoneUnicodePropertyNameOrValue UnicodePropertyName :: UnicodePropertyNameCharacters UnicodePropertyNameCharacters :: UnicodePropertyNameCharacter UnicodePropertyNameCharactersopt UnicodePropertyValue :: UnicodePropertyValueCharacters LoneUnicodePropertyNameOrValue :: UnicodePropertyValueCharacters UnicodePropertyValueCharacters :: UnicodePropertyValueCharacter UnicodePropertyValueCharactersopt UnicodePropertyValueCharacter :: UnicodePropertyNameCharacter DecimalDigit UnicodePropertyNameCharacter :: AsciiLetter _ CharacterClass[UnicodeMode, UnicodeSetsMode] :: [ [lookahead ≠ ^] ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] [^ ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] ClassContents[UnicodeMode, UnicodeSetsMode] :: [empty] [~UnicodeSetsMode] NonemptyClassRanges[?UnicodeMode] [+UnicodeSetsMode] ClassSetExpression NonemptyClassRanges[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtom[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtom[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] NonemptyClassRangesNoDash[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] ClassAtom[UnicodeMode] :: - ClassAtomNoDash[?UnicodeMode] ClassAtomNoDash[UnicodeMode] :: SourceCharacter but not one of \ or ] or - \ ClassEscape[?UnicodeMode] ClassEscape[UnicodeMode] :: b [+UnicodeMode] - CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode] ClassSetExpression :: ClassUnion ClassIntersection ClassSubtraction ClassUnion :: ClassSetRange ClassUnionopt ClassSetOperand ClassUnionopt ClassIntersection :: ClassSetOperand && [lookahead ≠ &] ClassSetOperand ClassIntersection && [lookahead ≠ &] ClassSetOperand ClassSubtraction :: ClassSetOperand -- ClassSetOperand ClassSubtraction -- ClassSetOperand ClassSetRange :: ClassSetCharacter - ClassSetCharacter ClassSetOperand :: NestedClass ClassStringDisjunction ClassSetCharacter NestedClass :: [ [lookahead ≠ ^] ClassContents[+UnicodeMode, +UnicodeSetsMode] ] [^ ClassContents[+UnicodeMode, +UnicodeSetsMode] ] \ CharacterClassEscape[+UnicodeMode] 注 1

这里的前两行等价于 CharacterClass。

ClassStringDisjunction :: \q{ ClassStringDisjunctionContents } ClassStringDisjunctionContents :: ClassString ClassString | ClassStringDisjunctionContents ClassString :: [empty] NonEmptyClassString NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt ClassSetCharacter :: [lookahead ∉ ClassSetReservedDoublePunctuator] SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape[+UnicodeMode] \ ClassSetReservedPunctuator \b ClassSetReservedDoublePunctuator :: one of && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ ClassSetSyntaxCharacter :: one of ( ) [ ] { } / - \ | ClassSetReservedPunctuator :: one of & - ! # % , : ; < = > @ ` ~ 注 2

本节中的若干产生式在 B.1.2 中给出了替代定义。

22.2.1.1 Static Semantics: 提前错误

注

本节在 B.1.2.1 中进行了修订。

Pattern :: Disjunction QuantifierPrefix :: { DecimalDigits , DecimalDigits } Atom :: (? RegularExpressionModifiers : Disjunction ) Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction ) AtomEscape :: k GroupName AtomEscape :: DecimalEscape NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue CharacterClassEscape :: P{ UnicodePropertyValueExpression } CharacterClass :: [^ ClassContents ] NestedClass :: [^ ClassContents ] ClassSetRange :: ClassSetCharacter - ClassSetCharacter

22.2.1.2 Static Semantics: CountLeftCapturingParensWithin ( parseNode )

抽象操作 CountLeftCapturingParensWithin,接收参数 parseNode (解析节点);返回值:非负整数。 它返回 parseNode 中左捕获括号的数量。左捕获括号是由 Atom :: ( GroupSpecifieropt Disjunction ) 产生式的 ( 终结符匹配的任何 ( 模式字符。

注

本节在 B.1.2.2 中进行了修订。

调用时执行以下步骤:

  1. 断言:parseNode 是 RegExp Pattern 文法中某个产生式的实例。
  2. 返回 parseNode 中包含的 Atom :: ( GroupSpecifieropt Disjunction ) Parse Node 的数量。

22.2.1.3 Static Semantics: CountLeftCapturingParensBefore ( parseNode )

抽象操作 CountLeftCapturingParensBefore,接收参数 parseNode (解析节点);返回值:非负整数。 它返回外围模式中位于 parseNode 左侧的左捕获括号数量。

注

本节在 B.1.2.2 中进行了修订。

调用时执行以下步骤:

  1. 断言:parseNode 是 RegExp Pattern 文法中某个产生式的实例。
  2. 令 pattern 为包含 parseNode 的 Pattern。
  3. 返回 pattern 中包含的、要么出现在 parseNode 之前,要么包含 parseNode 的 Atom :: ( GroupSpecifieropt Disjunction ) Parse Node 的数量。

22.2.1.4 Static Semantics: MightBothParticipate ( x, y )

抽象操作 MightBothParticipate,接收参数 x (解析节点) 和 y (解析节点);返回值:Boolean。 调用时执行以下步骤:

  1. 断言:x 和 y 具有相同的外围 Pattern。
  2. 如果外围 Pattern 包含一个 Disjunction :: Alternative | Disjunction Parse Node,并且 x 包含在 Alternative 中且 y 包含在派生的 Disjunction 中,或者 x 包含在派生的 Disjunction 中且 y 包含在 Alternative 中,则返回 false。
  3. 返回 true。

22.2.1.5 Static Semantics: CapturingGroupNumber

语法制导操作 CapturingGroupNumber,接收无参数;返回值:正整数。

注

本节在 B.1.2.1 中进行了修订。

它按以下产生式分别定义:

DecimalEscape :: NonZeroDigit
  1. 返回 NonZeroDigit 的 MV。
DecimalEscape :: NonZeroDigit DecimalDigits
  1. 令 n 为 DecimalDigits 中的码点数量。
  2. 返回(NonZeroDigit 的 MV × 10n 加上 DecimalDigits 的 MV)。

“NonZeroDigit 的 MV”和“DecimalDigits 的 MV”的定义见 12.9.3。

22.2.1.6 Static Semantics: IsCharacterClass

语法制导操作 IsCharacterClass,接收无参数;返回值:Boolean。

注

本节在 B.1.2.3 中进行了修订。

它按以下产生式分别定义:

ClassAtom :: - ClassAtomNoDash :: SourceCharacter but not one of \ or ] or - ClassEscape :: b - CharacterEscape
  1. 返回 false。
ClassEscape :: CharacterClassEscape
  1. 返回 true。

22.2.1.7 Static Semantics: CharacterValue

语法制导操作 CharacterValue,接收无参数;返回值:非负整数。

注 1

本节在 B.1.2.4 中进行了修订。

它按以下产生式分别定义:

ClassAtom :: -
  1. 返回 U+002D (HYPHEN-MINUS) 的数值。
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. 令 codePoint 为 SourceCharacter 所匹配的码点。
  2. 返回 codePoint 的数值。
ClassEscape :: b
  1. 返回 U+0008 (BACKSPACE) 的数值。
ClassEscape :: -
  1. 返回 U+002D (HYPHEN-MINUS) 的数值。
CharacterEscape :: ControlEscape
  1. 按照 表 63 返回数值。
表 63: ControlEscape 码点值
ControlEscape 数值 码点 Unicode 名称 符号
t 9 U+0009 CHARACTER TABULATION <HT>
n 10 U+000A LINE FEED (LF) <LF>
v 11 U+000B LINE TABULATION <VT>
f 12 U+000C FORM FEED (FF) <FF>
r 13 U+000D CARRIAGE RETURN (CR) <CR>
CharacterEscape :: c AsciiLetter
  1. 令 codePoint 为 AsciiLetter 所匹配的码点。
  2. 令 i 为 codePoint 的数值。
  3. 返回 i 除以 32 的余数。
CharacterEscape :: 0 [lookahead ∉ DecimalDigit]
  1. 返回 U+0000 (NULL) 的数值。
注 2

\0 表示 <NUL> 字符,并且后面不能跟十进制数字。

CharacterEscape :: HexEscapeSequence
  1. 返回 HexEscapeSequence 的 MV。
RegExpUnicodeEscapeSequence :: u HexLeadSurrogate \u HexTrailSurrogate
  1. 令 lead 为 CharacterValue of HexLeadSurrogate。
  2. 令 trail 为 CharacterValue of HexTrailSurrogate。
  3. 令 codePoint 为 UTF16SurrogatePairToCodePoint(lead, trail)。
  4. 返回 codePoint 的数值。
RegExpUnicodeEscapeSequence :: u Hex4Digits
  1. 返回 Hex4Digits 的 MV。
RegExpUnicodeEscapeSequence :: u{ CodePoint }
  1. 返回 CodePoint 的 MV。
HexLeadSurrogate :: Hex4Digits HexTrailSurrogate :: Hex4Digits HexNonSurrogate :: Hex4Digits
  1. 返回 Hex4Digits 的 MV。
CharacterEscape :: IdentityEscape
  1. 令 codePoint 为 IdentityEscape 所匹配的码点。
  2. 返回 codePoint 的数值。
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter
  1. 令 codePoint 为 SourceCharacter 所匹配的码点。
  2. 返回 codePoint 的数值。
ClassSetCharacter :: \ ClassSetReservedPunctuator
  1. 令 codePoint 为 ClassSetReservedPunctuator 所匹配的码点。
  2. 返回 codePoint 的数值。
ClassSetCharacter :: \b
  1. 返回 U+0008 (BACKSPACE) 的数值。

22.2.1.8 Static Semantics: MayContainStrings

语法制导操作 MayContainStrings,接收无参数;返回值:Boolean。 它按以下产生式分别定义:

CharacterClassEscape :: d D s S w W P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue NestedClass :: [^ ClassContents ] ClassContents :: [empty] NonemptyClassRanges ClassSetOperand :: ClassSetCharacter
  1. 返回 false。
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. 如果 LoneUnicodePropertyNameOrValue 所匹配的源文本是 表 67 的“Property name”列中列出的字符串二元属性,则返回 true。
  2. 返回 false。
ClassUnion :: ClassSetRange ClassUnionopt
  1. 如果存在 ClassUnion,则返回 MayContainStrings of the ClassUnion。
  2. 返回 false。
ClassUnion :: ClassSetOperand ClassUnionopt
  1. 如果 MayContainStrings of the ClassSetOperand 是 true,则返回 true。
  2. 如果存在 ClassUnion,则返回 MayContainStrings of the ClassUnion。
  3. 返回 false。
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. 如果 MayContainStrings of the first ClassSetOperand 是 false,则返回 false。
  2. 如果 MayContainStrings of the second ClassSetOperand 是 false,则返回 false。
  3. 返回 true。
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. 如果 MayContainStrings of the ClassIntersection 是 false,则返回 false。
  2. 如果 MayContainStrings of the ClassSetOperand 是 false,则返回 false。
  3. 返回 true。
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. 返回 MayContainStrings of the first ClassSetOperand。
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. 返回 MayContainStrings of the ClassSubtraction。
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. 如果 MayContainStrings of the ClassString 是 true,则返回 true。
  2. 返回 MayContainStrings of the ClassStringDisjunctionContents。
ClassString :: [empty]
  1. 返回 true。
ClassString :: NonEmptyClassString
  1. 返回 MayContainStrings of the NonEmptyClassString。
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. 如果存在 NonEmptyClassString,则返回 true。
  2. 返回 false。

22.2.1.9 Static Semantics: GroupSpecifiersThatMatch ( thisGroupName )

抽象操作 GroupSpecifiersThatMatch,接收参数 thisGroupName (a GroupName Parse Node);返回值:列表 (元素:GroupSpecifier Parse Nodes)。 调用时执行以下步骤:

  1. 令 name 为 CapturingGroupName of thisGroupName。
  2. 令 pattern 为包含 thisGroupName 的 Pattern。
  3. 令 result 为新的空 List。
  4. 对 pattern 包含的每个 GroupSpecifier groupSpecifier,执行
    1. 如果 CapturingGroupName of groupSpecifier 是 name,则
      1. 将 groupSpecifier 追加到 result。
  5. 返回 result。

22.2.1.10 Static Semantics: CapturingGroupName

语法制导操作 CapturingGroupName,接收无参数;返回值:String。 它按以下产生式分别定义:

GroupName :: < RegExpIdentifierName >
  1. 令 nameUnescaped 为 RegExpIdentifierCodePoints of RegExpIdentifierName。
  2. 返回 CodePointsToString(nameUnescaped)。

22.2.1.11 Static Semantics: RegExpIdentifierCodePoints

语法制导操作 RegExpIdentifierCodePoints,接收无参数;返回值:列表 (元素:码点)。 它按以下产生式分别定义:

RegExpIdentifierName :: RegExpIdentifierStart
  1. 令 codePoint 为 RegExpIdentifierCodePoint of RegExpIdentifierStart。
  2. 返回 « codePoint »。
RegExpIdentifierName :: RegExpIdentifierName RegExpIdentifierPart
  1. 令 codePoints 为 RegExpIdentifierCodePoints of the derived RegExpIdentifierName。
  2. 令 codePoint 为 RegExpIdentifierCodePoint of RegExpIdentifierPart。
  3. 返回 codePoints 和 « codePoint » 的列表连接。

22.2.1.12 Static Semantics: RegExpIdentifierCodePoint

语法制导操作 RegExpIdentifierCodePoint,接收无参数;返回值:码点。 它按以下产生式分别定义:

RegExpIdentifierStart :: IdentifierStartChar
  1. 返回 IdentifierStartChar 所匹配的码点。
RegExpIdentifierPart :: IdentifierPartChar
  1. 返回 IdentifierPartChar 所匹配的码点。
RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence
  1. 返回数值等于 CharacterValue of RegExpUnicodeEscapeSequence 的码点。
RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate
  1. 令 lead 为数值等于 UnicodeLeadSurrogate 所匹配码点数值的码元。
  2. 令 trail 为数值等于 UnicodeTrailSurrogate 所匹配码点数值的码元。
  3. 返回 UTF16SurrogatePairToCodePoint(lead, trail)。

22.2.2 模式语义

正则表达式模式通过下面描述的过程转换为 Abstract Closure。只要结果相同,鼓励实现使用比下面列出的算法更高效的算法。该 Abstract Closure 用作 RegExp 对象的 [[RegExpMatcher]] 内部槽的值。

如果一个 Pattern 的相关标志既不包含 u 也不包含 v,则它是 BMP 模式。否则,它是 Unicode 模式。BMP 模式与被解释为由基本多文种平面范围内 Unicode 码点的 16 位值序列组成的 String 进行匹配。Unicode 模式与被解释为由使用 UTF-16 编码的 Unicode 码点组成的 String 进行匹配。在描述 BMP 模式行为的上下文中,“字符”表示单个 16 位 Unicode BMP 码点。在描述 Unicode 模式行为的上下文中,“字符”表示 UTF-16 编码的码点(6.1.4)。在任一上下文中,“字符值”表示相应未编码码点的数值。

Pattern 的语法和语义定义为如同 Pattern 的源文本是 SourceCharacter 值的 List,其中每个 SourceCharacter 对应一个 Unicode 码点。如果 BMP 模式包含非 BMP SourceCharacter,则整个模式使用 UTF-16 编码,并将该编码的各个码元用作 List 的元素。

注

例如,考虑一个在源文本中表示为单个非 BMP 字符 U+1D11E (MUSICAL SYMBOL G CLEF) 的模式。解释为 Unicode 模式时,它将是一个单元素(字符)List,其中包含单个码点 U+1D11E。不过,解释为 BMP 模式时,会先使用 UTF-16 编码,产生由码元 0xD834 和 0xDD1E 组成的双元素 List。

模式作为 ECMAScript String 值传递给 RegExp 构造函数,其中非 BMP 字符使用 UTF-16 编码。例如,表示为 String 值的单字符 MUSICAL SYMBOL G CLEF 模式是一个长度为 2 的 String,其元素是码元 0xD834 和 0xDD1E。因此,将其作为由两个模式字符组成的 BMP 模式处理时,不需要进一步转换该字符串。不过,要将其作为 Unicode 模式处理,必须使用 UTF16SurrogatePairToCodePoint 来生成一个 List,其唯一元素是单个模式字符,即码点 U+1D11E。

实现实际上可以不执行与 UTF-16 之间的此类转换,但本规范的语义要求模式匹配的结果如同执行了此类转换。

22.2.2.1 记号

以下描述使用下列内部数据结构:

  • CharSetElement 是以下两种实体之一:
    • 如果 regexpRecord.[[UnicodeSets]] 是 false,则 CharSetElement 是上述模式语义意义上的字符。
    • 如果 regexpRecord.[[UnicodeSets]] 是 true,则 CharSetElement 是一个序列,其元素是上述模式语义意义上的字符。这包括空序列、单字符序列以及多字符序列。为方便起见,在处理此类 CharSetElement 时,单个字符与单字符序列可互换使用。
  • CharSet 是 CharSetElement 的数学集合。
  • CaptureRange 是 Record { [[StartIndex]], [[EndIndex]] },表示捕获中所包含字符的范围,其中 [[StartIndex]] 是表示该范围在 input 中起始索引(包含)的整数,[[EndIndex]] 是表示该范围在 input 中结束索引(不包含)的整数。对于任何 CaptureRange,这些索引都必须满足 [[StartIndex]] ≤ [[EndIndex]] 这一不变量。
  • MatchState 是 Record { [[Input]], [[EndIndex]], [[Captures]] },其中 [[Input]] 是表示正在匹配的 String 的字符 List,[[EndIndex]] 是整数,[[Captures]] 是值的 List,模式中的每个左捕获括号对应一个值。MatchState 用于表示正则表达式匹配算法中的部分匹配状态。[[EndIndex]] 是模式迄今所匹配最后一个输入字符的索引加一,而 [[Captures]] 保存捕获括号的结果。[[Captures]] 的第 nth 个元素要么是表示第 nth 组捕获括号捕获字符范围的 CaptureRange,要么在尚未到达第 nth 组捕获括号时为 undefined。由于回溯,在匹配过程中任意时刻都可能同时使用许多 MatchState。
  • MatcherContinuation 是一个接受一个 MatchState 参数,并返回 MatchState 或 failure 的 Abstract Closure。MatcherContinuation 尝试从其 MatchState 参数给出的中间状态开始,将模式的剩余部分(由闭包捕获的值指定)与 input 进行匹配。如果匹配成功,MatcherContinuation 返回其到达的最终 MatchState;如果匹配失败,则 MatcherContinuation 返回 failure。
  • Matcher 是一个接受两个参数——MatchState 和 MatcherContinuation——并返回 MatchState 或 failure 的 Abstract Closure。Matcher 尝试从其 MatchState 参数给出的中间状态开始,将模式的中间子模式(由闭包捕获的值指定)与该 MatchState 的 [[Input]] 进行匹配。MatcherContinuation 参数应是一个用于匹配模式剩余部分的闭包。在匹配模式的子模式并得到新的 MatchState 后,Matcher 随后使用该新 MatchState 调用 MatcherContinuation,以测试模式的其余部分是否也能匹配。如果可以,Matcher 返回 MatcherContinuation 返回的 MatchState;如果不可以,Matcher 可以在其选择点尝试不同选择,反复调用 MatcherContinuation,直到成功或所有可能性都已穷尽。

22.2.2.1.1 RegExp Record

RegExp Record 是用于存储编译期间以及可能在匹配期间所需 RegExp 信息的 Record。

它具有以下字段:

表 64: RegExp Record 字段
字段名称 值 含义
[[IgnoreCase]] a Boolean 表示 "i" 是否出现在 RegExp 的标志中
[[Multiline]] a Boolean 表示 "m" 是否出现在 RegExp 的标志中
[[DotAll]] a Boolean 表示 "s" 是否出现在 RegExp 的标志中
[[Unicode]] a Boolean 表示 "u" 是否出现在 RegExp 的标志中
[[UnicodeSets]] a Boolean 表示 "v" 是否出现在 RegExp 的标志中
[[CapturingGroupsCount]] a non-negative integer RegExp 模式中左捕获括号的数量

22.2.2.2 Runtime Semantics: CompilePattern

语法制导操作 CompilePattern,接收参数 regexpRecord (RegExp 记录);返回值:an Abstract Closure that takes a List of characters and a non-negative integer and returns either a MatchState or failure。 它按以下产生式分别定义:

Pattern :: Disjunction
  1. 令 m 为 CompileSubpattern of Disjunction with arguments regexpRecord and forward。
  2. 返回一个参数为 (input, index) 的新 Abstract Closure,它捕获 regexpRecord 和 m,并在被调用时执行以下步骤:
    1. 断言:input 是字符 List。
    2. 断言:0 ≤ index ≤ input 中的元素数量。
    3. 令 c 为参数为 (y) 的新 MatcherContinuation,它不捕获任何内容,并在被调用时执行以下步骤:
      1. 断言:y 是 MatchState。
      2. 返回 y。
    4. 令 capability 为由 regexpRecord.[[CapturingGroupsCount]] 个 undefined 值组成的 List,索引从 1 到 regexpRecord.[[CapturingGroupsCount]]。
    5. 令 x 为 MatchState { [[Input]]: input, [[EndIndex]]: index, [[Captures]]: capability }。
    6. 返回 m(x, c)。
注

Pattern 会编译为 Abstract Closure 值。随后,RegExpBuiltinExec 可以将此过程应用于字符 List 和该 List 中的偏移量,以确定模式是否恰好从该偏移量开始匹配;如果匹配,则确定捕获括号的值。22.2.2 中的算法被设计为:编译模式可能抛出 SyntaxError 异常;另一方面,一旦模式成功编译,将所得 Abstract Closure 应用于字符 List 以查找匹配时不会抛出异常(除了任何可能在任意位置发生的实现定义异常,例如内存不足)。

22.2.2.3 Runtime Semantics: CompileSubpattern

语法制导操作 CompileSubpattern,接收参数 regexpRecord (RegExp 记录) 和 direction ((forward 或 backward));返回值:Matcher。

注 1

本节在 B.1.2.5 中进行了修订。

它按以下产生式分别定义:

Disjunction :: Alternative | Disjunction
  1. 令 m1 为 CompileSubpattern of Alternative with arguments regexpRecord and direction。
  2. 令 m2 为 CompileSubpattern of Disjunction with arguments regexpRecord and direction。
  3. 返回 MatchTwoAlternatives(m1, m2)。
注 2

| 正则表达式运算符分隔两个备选项。模式首先尝试匹配左侧 Alternative(后接正则表达式的后续部分);如果失败,则尝试匹配右侧 Disjunction(后接正则表达式的后续部分)。如果左侧 Alternative、右侧 Disjunction 和后续部分都有选择点,则在转到左侧 Alternative 中的下一个选择之前,会先尝试后续部分中的所有选择。如果左侧 Alternative 中的选择已经穷尽,则会尝试右侧 Disjunction,而不是左侧 Alternative。由 | 跳过的模式部分中的任何捕获括号都会产生 undefined 值而不是 Strings。因此,例如,

/a|ab/.exec("abc")

返回结果 "a",而不是 "ab"。此外,

/((a)|(ab))((c)|(bc))/.exec("abc")

返回数组

["abc", "a", "a", undefined, "bc", undefined, "bc"]

而不是

["abc", "ab", undefined, "ab", "c", "c", undefined]

尝试两个备选项的顺序与 direction 的值无关。

Alternative :: [empty]
  1. 返回 EmptyMatcher()。
Alternative :: Alternative Term
  1. 令 m1 为 CompileSubpattern of Alternative with arguments regexpRecord and direction。
  2. 令 m2 为 CompileSubpattern of Term with arguments regexpRecord and direction。
  3. 返回 MatchSequence(m1, m2, direction)。
注 3

连续的 Term 会尝试同时匹配 input 中连续的部分。当 direction 是 forward 时,如果左侧 Alternative、右侧 Term 和正则表达式的后续部分都有选择点,则在转到右侧 Term 中的下一个选择之前,会先尝试后续部分中的所有选择,而在转到左侧 Alternative 中的下一个选择之前,会尝试右侧 Term 中的所有选择。当 direction 是 backward 时,Alternative 和 Term 的求值顺序相反。

Term :: Assertion
  1. 返回 CompileAssertion of Assertion with argument regexpRecord。
注 4

所得 Matcher 与 direction 无关。

Term :: Atom
  1. 返回 CompileAtom of Atom with arguments regexpRecord and direction。
Term :: Atom Quantifier
  1. 令 m 为 CompileAtom of Atom with arguments regexpRecord and direction。
  2. 令 q 为 CompileQuantifier of Quantifier。
  3. 断言:q.[[Min]] ≤ q.[[Max]]。
  4. 令 parenIndex 为 CountLeftCapturingParensBefore(Term)。
  5. 令 parenCount 为 CountLeftCapturingParensWithin(Atom)。
  6. 返回一个参数为 (x, c) 的新 Matcher,它捕获 m、q、parenIndex 和 parenCount,并在被调用时执行以下步骤:
    1. 断言:x 是 MatchState。
    2. 断言:c 是 MatcherContinuation。
    3. 返回 RepeatMatcher(m, q.[[Min]], q.[[Max]], q.[[Greedy]], x, c, parenIndex, parenCount)。

22.2.2.3.1 RepeatMatcher ( m, min, max, greedy, matchState, continue, parenIndex, parenCount )

抽象操作 RepeatMatcher,接收参数 m (Matcher)、min (非负整数)、max ((非负整数 或 +∞))、greedy (Boolean)、matchState (MatchState)、continue (MatcherContinuation)、parenIndex (非负整数) 和 parenCount (非负整数);返回值:(MatchState 或 failure)。 调用时执行以下步骤:

  1. 如果 max = 0,则返回 continue(matchState)。
  2. 令 d 为参数为 (y) 的新 MatcherContinuation,它捕获 m、min、max、greedy、matchState、continue、parenIndex 和 parenCount,并在被调用时执行以下步骤:
    1. 断言:y 是 MatchState。
    2. 如果 min = 0 且 y.[[EndIndex]] = matchState.[[EndIndex]],则返回 failure。
    3. 如果 min = 0,则令 min2 为 0;否则令 min2 为 min - 1。
    4. 如果 max = +∞,则令 max2 为 +∞;否则令 max2 为 max - 1。
    5. 返回 RepeatMatcher(m, min2, max2, greedy, y, continue, parenIndex, parenCount)。
  3. 令 capability 为 matchState.[[Captures]] 的副本。
  4. 对从 parenIndex + 1 到 parenIndex + parenCount 闭区间内的每个整数 k,将 capability[k] 设置为 undefined。
  5. 令 input 为 matchState.[[Input]]。
  6. 令 e 为 matchState.[[EndIndex]]。
  7. 令 xr 为 MatchState { [[Input]]: input, [[EndIndex]]: e, [[Captures]]: capability }。
  8. 如果 min ≠ 0,则返回 m(xr, d)。
  9. 如果 greedy 是 false,则
    1. 令 z 为 continue(matchState)。
    2. 如果 z 不是 failure,则返回 z。
    3. 返回 m(xr, d)。
  10. 令 z 为 m(xr, d)。
  11. 如果 z 不是 failure,则返回 z。
  12. 返回 continue(matchState)。
注 1

后跟 Quantifier 的 Atom 会按 Quantifier 指定的次数重复。Quantifier 可以是非贪婪的,在这种情况下,Atom 模式会在仍能匹配后续部分的前提下尽可能少地重复;也可以是贪婪的,在这种情况下,Atom 模式会在仍能匹配后续部分的前提下尽可能多地重复。重复的是 Atom 模式,而不是它所匹配的输入字符序列,因此 Atom 的不同重复可以匹配不同的输入子字符串。

注 2

如果 Atom 和正则表达式的后续部分都有选择点,则首先尽可能多次(若为非贪婪则尽可能少次)匹配 Atom。在转到 Atom 最后一次重复中的下一个选择之前,会先尝试后续部分中的所有选择。在转到 Atom 倒数第二次(第 (n - 1)st 次)重复中的下一个选择之前,会先尝试 Atom 最后一次(第 nth 次)重复中的所有选择;此时可能会发现现在可以进行更多或更少的 Atom 重复;在转到第 (n - 1)st 次 Atom 重复中的下一个选择之前,会再次穷尽这些可能性(仍从尽可能少或尽可能多开始),依此类推。

比较

/a[a-z]{2,4}/.exec("abcdefghi")

它返回 "abcde",与

/a[a-z]{2,4}?/.exec("abcdefghi")

相比,后者返回 "abc"。

还可考虑

/(aa|aabaac|ba|b|c)*/.exec("aabaac")

根据上述选择点顺序,它返回数组

["aaba", "ba"]

而不是以下任何一个:

["aabaac", "aabaac"]
["aabaac", "c"]

上述选择点顺序可以用于编写一个正则表达式,计算两个数字(用一元表示法表示)的最大公约数。以下示例计算 10 和 15 的最大公约数:

"aaaaaaaaaa,aaaaaaaaaaaaaaa".replace(/^(a+)\1*,\1+$/, "$1")

它以一元表示法返回最大公约数 "aaaaa"。

注 3

RepeatMatcher 的步骤 4 会在每次重复 Atom 时清除 Atom 的捕获。我们可以在以下正则表达式中观察其行为

/(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")

它返回数组

["zaacbbbcac", "z", "ac", "a", undefined, "c"]

而不是

["zaacbbbcac", "z", "ac", "a", "bbb", "c"]

因为最外层 * 的每次迭代都会清除量化 Atom 中包含的所有捕获 String,在本例中包括编号 2、3、4 和 5 的捕获 String。

注 4

RepeatMatcher 的步骤 2.b 规定,一旦满足最小重复次数,就不再考虑与空字符序列匹配的 Atom 的更多展开来进行后续重复。这可以防止正则表达式引擎在如下模式上陷入无限循环:

/(a*)*/.exec("b")

或者稍微复杂一点的:

/(a*)b\1+/.exec("baaaac")

它返回数组

["b", ""]

22.2.2.3.2 EmptyMatcher ( )

抽象操作 EmptyMatcher,接收无参数;返回值:Matcher。 调用时执行以下步骤:

  1. 返回一个参数为 (matchState, continue) 的新 Matcher,它不捕获任何内容,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 返回 continue(matchState)。

22.2.2.3.3 MatchTwoAlternatives ( m1, m2 )

抽象操作 MatchTwoAlternatives,接收参数 m1 (Matcher) 和 m2 (Matcher);返回值:Matcher。 调用时执行以下步骤:

  1. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 m1 和 m2,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 result 为 m1(matchState, continue)。
    4. 如果 result 不是 failure,则返回 result。
    5. 返回 m2(matchState, continue)。

22.2.2.3.4 MatchSequence ( m1, m2, direction )

抽象操作 MatchSequence,接收参数 m1 (Matcher)、m2 (Matcher) 和 direction ((forward 或 backward));返回值:Matcher。 调用时执行以下步骤:

  1. 如果 direction 是 forward,则
    1. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 m1 和 m2,并在被调用时执行以下步骤:
      1. 断言:matchState 是 MatchState。
      2. 断言:continue 是 MatcherContinuation。
      3. 令 d 为参数为 (y) 的新 MatcherContinuation,它捕获 continue 和 m2,并在被调用时执行以下步骤:
        1. 断言:y 是 MatchState。
        2. 返回 m2(y, continue)。
      4. 返回 m1(matchState, d)。
  2. 断言:direction 是 backward。
  3. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 m1 和 m2,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 d 为参数为 (y) 的新 MatcherContinuation,它捕获 continue 和 m1,并在被调用时执行以下步骤:
      1. 断言:y 是 MatchState。
      2. 返回 m1(y, continue)。
    4. 返回 m2(matchState, d)。

22.2.2.4 Runtime Semantics: CompileAssertion

语法制导操作 CompileAssertion,接收参数 regexpRecord (RegExp 记录);返回值:Matcher。

注 1

本节在 B.1.2.6 中进行了修订。

它按以下产生式分别定义:

Assertion :: ^
  1. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 regexpRecord,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 input 为 matchState.[[Input]]。
    4. 令 e 为 matchState.[[EndIndex]]。
    5. 如果 e = 0,或者 regexpRecord.[[Multiline]] 是 true 且字符 input[e - 1] 被 LineTerminator 匹配,则
      1. 返回 continue(matchState)。
    6. 返回 failure。
注 2

即使模式使用 y 标志,^ 仍始终只在 input 的开头匹配,或者(如果 regexpRecord.[[Multiline]] 是 true)在某行开头匹配。

Assertion :: $
  1. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 regexpRecord,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 input 为 matchState.[[Input]]。
    4. 令 e 为 matchState.[[EndIndex]]。
    5. 令 inputLength 为 input 中的元素数量。
    6. 如果 e = inputLength,或者 regexpRecord.[[Multiline]] 是 true 且字符 input[e] 被 LineTerminator 匹配,则
      1. 返回 continue(matchState)。
    7. 返回 failure。
Assertion :: \b
  1. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 regexpRecord,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 input 为 matchState.[[Input]]。
    4. 令 e 为 matchState.[[EndIndex]]。
    5. 令 a 为 IsWordChar(regexpRecord, input, e - 1)。
    6. 令 b 为 IsWordChar(regexpRecord, input, e)。
    7. 如果 a 是 true 且 b 是 false,或者 a 是 false 且 b 是 true,则返回 continue(matchState)。
    8. 返回 failure。
Assertion :: \B
  1. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 regexpRecord,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 input 为 matchState.[[Input]]。
    4. 令 e 为 matchState.[[EndIndex]]。
    5. 令 a 为 IsWordChar(regexpRecord, input, e - 1)。
    6. 令 b 为 IsWordChar(regexpRecord, input, e)。
    7. 如果 a 是 true 且 b 是 true,或者 a 是 false 且 b 是 false,则返回 continue(matchState)。
    8. 返回 failure。
Assertion :: (?= Disjunction )
  1. 令 m 为 CompileSubpattern of Disjunction with arguments regexpRecord and forward。
  2. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 m,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 d 为参数为 (y) 的新 MatcherContinuation,它不捕获任何内容,并在被调用时执行以下步骤:
      1. 断言:y 是 MatchState。
      2. 返回 y。
    4. 令 result 为 m(matchState, d)。
    5. 如果 result 是 failure,则返回 failure。
    6. 断言:result 是 MatchState。
    7. 令 capability 为 result.[[Captures]]。
    8. 令 input 为 matchState.[[Input]]。
    9. 令 xe 为 matchState.[[EndIndex]]。
    10. 令 z 为 MatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: capability }。
    11. 返回 continue(z)。
注 3

形式 (?= Disjunction ) 指定零宽正向先行断言。要使其成功,Disjunction 内的模式必须在当前位置匹配,但在匹配后续部分之前不会推进当前位置。如果 Disjunction 能以多种方式在当前位置匹配,只尝试第一种。与其他正则表达式运算符不同,不会回溯进入 (?= 形式(这种不寻常的行为继承自 Perl)。只有当 Disjunction 包含捕获括号且模式的后续部分包含对这些捕获的反向引用时,这一点才有影响。

例如,

/(?=(a+))/.exec("baaabac")

会匹配第一个 b 之后紧接的空 String,因此返回数组:

["", "aaa"]

为说明先行断言中不会发生回溯,请考虑:

/(?=(a+))a*b\1/.exec("baaabac")

此表达式返回

["aba", "a"]

而不是:

["aaaba", "a"]
Assertion :: (?! Disjunction )
  1. 令 m 为 CompileSubpattern of Disjunction with arguments regexpRecord and forward。
  2. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 m,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 d 为参数为 (y) 的新 MatcherContinuation,它不捕获任何内容,并在被调用时执行以下步骤:
      1. 断言:y 是 MatchState。
      2. 返回 y。
    4. 令 result 为 m(matchState, d)。
    5. 如果 result 不是 failure,则返回 failure。
    6. 返回 continue(matchState)。
注 4

形式 (?! Disjunction ) 指定零宽负向先行断言。要使其成功,Disjunction 内的模式必须无法在当前位置匹配。在匹配后续部分之前不会推进当前位置。Disjunction 可以包含捕获括号,但对它们的反向引用只有从 Disjunction 自身内部使用才有意义。模式中其他位置对这些捕获括号的反向引用始终返回 undefined,因为负向先行断言必须失败,整个模式才能成功。例如,

/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac")

会查找一个 a,其后不能紧跟某个正整数 n 个 a、一个 b、另一个 n 个 a(由第一个 \2 指定)以及一个 c。第二个 \2 位于负向先行断言之外,因此它与 undefined 匹配,从而始终成功。整个表达式返回数组:

["baaabaac", "ba", undefined, "abaac"]
Assertion :: (?<= Disjunction )
  1. 令 m 为 CompileSubpattern of Disjunction with arguments regexpRecord and backward。
  2. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 m,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 d 为参数为 (y) 的新 MatcherContinuation,它不捕获任何内容,并在被调用时执行以下步骤:
      1. 断言:y 是 MatchState。
      2. 返回 y。
    4. 令 result 为 m(matchState, d)。
    5. 如果 result 是 failure,则返回 failure。
    6. 断言:result 是 MatchState。
    7. 令 capability 为 result.[[Captures]]。
    8. 令 input 为 matchState.[[Input]]。
    9. 令 xe 为 matchState.[[EndIndex]]。
    10. 令 z 为 MatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: capability }。
    11. 返回 continue(z)。
Assertion :: (?<! Disjunction )
  1. 令 m 为 CompileSubpattern of Disjunction with arguments regexpRecord and backward。
  2. 返回一个参数为 (matchState, continue) 的新 Matcher,它捕获 m,并在被调用时执行以下步骤:
    1. 断言:matchState 是 MatchState。
    2. 断言:continue 是 MatcherContinuation。
    3. 令 d 为参数为 (y) 的新 MatcherContinuation,它不捕获任何内容,并在被调用时执行以下步骤:
      1. 断言:y 是 MatchState。
      2. 返回 y。
    4. 令 result 为 m(matchState, d)。
    5. 如果 result 不是 failure,则返回 failure。
    6. 返回 continue(matchState)。

22.2.2.4.1 IsWordChar ( regexpRecord, input, e )

抽象操作 IsWordChar,接收参数 regexpRecord (RegExp 记录)、input (列表 (元素:字符)) 和 e (整数);返回值:Boolean。 调用时执行以下步骤:

  1. 令 inputLength 为 input 中的元素数量。
  2. 如果 e = -1 或 e = inputLength,则返回 false。
  3. 令 char 为字符 input[e]。
  4. 如果 WordCharacters(regexpRecord) 包含 char,则返回 true。
  5. 返回 false。

22.2.2.5 Runtime Semantics: CompileQuantifier

语法制导操作 CompileQuantifier,接收无参数;返回值:记录 (字段:[[Min]] (非负整数), [[Max]] ((非负整数 或 +∞)), [[Greedy]] (Boolean))。 它按以下产生式分别定义:

Quantifier :: QuantifierPrefix
  1. 令 qp 为 CompileQuantifierPrefix of QuantifierPrefix。
  2. 返回 Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: true }。
Quantifier :: QuantifierPrefix ?
  1. 令 qp 为 CompileQuantifierPrefix of QuantifierPrefix。
  2. 返回 Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: false }。

22.2.2.6 Runtime Semantics: CompileQuantifierPrefix

语法制导操作 CompileQuantifierPrefix,接收无参数;返回值:记录 (字段:[[Min]] (非负整数), [[Max]] ((非负整数 或 +∞)))。 它按以下产生式分别定义:

QuantifierPrefix :: *
  1. 返回 Record { [[Min]]: 0, [[Max]]: +∞ }。
QuantifierPrefix :: +
  1. 返回 Record { [[Min]]: 1, [[Max]]: +∞ }。
QuantifierPrefix :: ?
  1. 返回 Record { [[Min]]: 0, [[Max]]: 1 }。
QuantifierPrefix :: { DecimalDigits }
  1. 令 i 为 DecimalDigits 的 MV(参见 12.9.3)。
  2. 返回 Record { [[Min]]: i, [[Max]]: i }。
QuantifierPrefix :: { DecimalDigits ,}
  1. 令 i 为 DecimalDigits 的 MV。
  2. 返回 Record { [[Min]]: i, [[Max]]: +∞ }。
QuantifierPrefix :: { DecimalDigits , DecimalDigits }
  1. 令 i 为第一个 DecimalDigits 的 MV。
  2. 令 j 为第二个 DecimalDigits 的 MV。
  3. 返回 Record { [[Min]]: i, [[Max]]: j }。

22.2.2.7 Runtime Semantics: CompileAtom

语法制导操作 CompileAtom,接收参数 regexpRecord (RegExp 记录) 和 direction ((forward 或 backward));返回值:Matcher。

注 1

本节在 B.1.2.7 中进行了修订。

它按以下产生式分别定义:

Atom :: PatternCharacter
  1. 令 char 为 PatternCharacter 所匹配的字符。
  2. 令 charSet 为包含字符 char 的单元素 CharSet。
  3. 返回 CharacterSetMatcher(regexpRecord, charSet, false, direction)。
Atom :: .
  1. 令 charSet 为 AllCharacters(regexpRecord)。
  2. 如果 regexpRecord.[[DotAll]] 不是 true,则
    1. 从 charSet 中移除与 LineTerminator 产生式右侧码点对应的所有字符。
  3. 返回 CharacterSetMatcher(regexpRecord, charSet, false, direction)。
Atom :: CharacterClass
  1. 令 cc 为 CompileCharacterClass of CharacterClass with argument regexpRecord。
  2. 令 cs 为 cc.[[CharSet]]。
  3. 如果 regexpRecord.[[UnicodeSets]] 是 false,或者 cs 的每个 CharSetElement 都由单个字符组成(包括 cs 为空的情况),则返回 CharacterSetMatcher(regexpRecord, cs, cc.[[Invert]], direction)。
  4. 断言:cc.[[Invert]] 是 false。
  5. 令 listOfMatchers 为空的 Matcher List。
  6. 令 csSequences 为新的空 List。
  7. 对 cs 的每个 CharSetElement s,执行
    1. 如果 s 的长度 > 1,则将 s 追加到 csSequences。
  8. 按每个 CharSetElement 的长度降序对 csSequences 排序。
  9. 对 csSequences 的每个 CharSetElement s,执行
    1. 断言:s 是由 2 个或更多码点组成的序列。
    2. 令 remaining 为由 s 的码点组成的 List。
    3. 令 cs2 为包含 remaining 最后一个元素的单元素 CharSet。
    4. 令 m2 为 CharacterSetMatcher(regexpRecord, cs2, false, direction)。
    5. 移除 remaining 的最后一个元素。
    6. 按 List 逆序,对 remaining 的每个码点 c1,执行
      1. 令 cs1 为包含 c1 的单元素 CharSet。
      2. 令 m1 为 CharacterSetMatcher(regexpRecord, cs1, false, direction)。
      3. 将 m2 设置为 MatchSequence(m1, m2, direction)。
    7. 将 m2 追加到 listOfMatchers。
  10. 令 singles 为由 cs 中所有只包含单个字符的 CharSetElement 组成的 CharSet。
  11. 将 CharacterSetMatcher(regexpRecord, singles, false, direction) 追加到 listOfMatchers。
  12. 如果 cs 包含空字符序列,则将 EmptyMatcher() 追加到 listOfMatchers。
  13. 令 m2 为 listOfMatchers 中最后一个 Matcher。
  14. 从倒数第二个元素开始反向迭代,对 listOfMatchers 的每个 Matcher m1,执行
    1. 将 m2 设置为 MatchTwoAlternatives(m1, m2)。
  15. 返回 m2。
Atom :: ( GroupSpecifieropt Disjunction )
  1. 令 m 为 CompileSubpattern of Disjunction with arguments regexpRecord and direction。
  2. 令 parenIndex 为 CountLeftCapturingParensBefore(Atom)。
  3. 返回一个参数为 (x, c) 的新 Matcher,它捕获 direction、m 和 parenIndex,并在被调用时执行以下步骤:
    1. 断言:x 是 MatchState。
    2. 断言:c 是 MatcherContinuation。
    3. 令 d 为参数为 (y) 的新 MatcherContinuation,它捕获 x、c、direction 和 parenIndex,并在被调用时执行以下步骤:
      1. 断言:y 是 MatchState。
      2. 令 capability 为 y.[[Captures]] 的副本。
      3. 令 input 为 x.[[Input]]。
      4. 令 xe 为 x.[[EndIndex]]。
      5. 令 ye 为 y.[[EndIndex]]。
      6. 如果 direction 是 forward,则
        1. 断言:xe ≤ ye。
        2. 令 r 为 CaptureRange { [[StartIndex]]: xe, [[EndIndex]]: ye }。
      7. 否则,
        1. 断言:direction 是 backward。
        2. 断言:ye ≤ xe。
        3. 令 r 为 CaptureRange { [[StartIndex]]: ye, [[EndIndex]]: xe }。
      8. 将 capability[parenIndex + 1] 设置为 r。
      9. 令 z 为 MatchState { [[Input]]: input, [[EndIndex]]: ye, [[Captures]]: capability }。
      10. 返回 c(z)。
    4. 返回 m(x, d)。
注 2

形式 ( Disjunction ) 的括号既用于将 Disjunction 模式的组成部分组合在一起,也用于保存匹配结果。该结果可以用于反向引用(\ 后跟非零十进制数)、在替换 String 中引用,或者作为正则表达式匹配 Abstract Closure 返回的数组的一部分。要抑制括号的捕获行为,请改用形式 (?: Disjunction )。

Atom :: (? RegularExpressionModifiers : Disjunction )
  1. 令 addModifiers 为 RegularExpressionModifiers 所匹配的源文本。
  2. 令 removeModifiers 为空 String。
  3. 令 modifiedRer 为 UpdateModifiers(regexpRecord, CodePointsToString(addModifiers), removeModifiers)。
  4. 返回 CompileSubpattern of Disjunction with arguments modifiedRer and direction。
Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction )
  1. 令 addModifiers 为第一个 RegularExpressionModifiers 所匹配的源文本。
  2. 令 removeModifiers 为第二个 RegularExpressionModifiers 所匹配的源文本。
  3. 令 modifiedRer 为 UpdateModifiers(regexpRecord, CodePointsToString(addModifiers), CodePointsToString(removeModifiers))。
  4. 返回 CompileSubpattern of Disjunction with arguments modifiedRer and direction。
AtomEscape :: DecimalEscape
  1. 令 n 为 CapturingGroupNumber of DecimalEscape。
  2. 断言:n ≤ regexpRecord.[[CapturingGroupsCount]]。
  3. 返回 BackreferenceMatcher(regexpRecord, « n », direction)。
注 3

形式为 \ 后跟非零十进制数 n 的转义序列会匹配第 nth 组捕获括号(22.2.2.1)的结果。如果正则表达式的捕获括号少于 n 个,则这是错误。如果正则表达式有 n 个或更多捕获括号,但第 nth 个因为尚未捕获任何内容而是 undefined,则反向引用始终成功。

AtomEscape :: CharacterEscape
  1. 令 charValue 为 CharacterValue of CharacterEscape。
  2. 令 char 为字符值等于 charValue 的字符。
  3. 令 charSet 为包含字符 char 的单元素 CharSet。
  4. 返回 CharacterSetMatcher(regexpRecord, charSet, false, direction)。
AtomEscape :: CharacterClassEscape
  1. 令 cs 为 CompileToCharSet of CharacterClassEscape with argument regexpRecord。
  2. 如果 regexpRecord.[[UnicodeSets]] 是 false,或者 cs 的每个 CharSetElement 都由单个字符组成(包括 cs 为空的情况),则返回 CharacterSetMatcher(regexpRecord, cs, false, direction)。
  3. 令 listOfMatchers 为空的 Matcher List。
  4. 令 csSequences 为新的空 List。
  5. 对 cs 的每个 CharSetElement s,执行
    1. 如果 s 的长度 > 1,则将 s 追加到 csSequences。
  6. 按每个 CharSetElement 的长度降序对 csSequences 排序。
  7. 对 csSequences 的每个 CharSetElement s,执行
    1. 断言:s 是由 2 个或更多码点组成的序列。
    2. 令 remaining 为由 s 的码点组成的 List。
    3. 令 cs2 为包含 remaining 最后一个元素的单元素 CharSet。
    4. 令 m2 为 CharacterSetMatcher(regexpRecord, cs2, false, direction)。
    5. 移除 remaining 的最后一个元素。
    6. 按 List 逆序,对 remaining 的每个码点 c1,执行
      1. 令 cs1 为包含 c1 的单元素 CharSet。
      2. 令 m1 为 CharacterSetMatcher(regexpRecord, cs1, false, direction)。
      3. 将 m2 设置为 MatchSequence(m1, m2, direction)。
    7. 将 m2 追加到 listOfMatchers。
  8. 令 singles 为由 cs 中所有只包含单个字符的 CharSetElement 组成的 CharSet。
  9. 将 CharacterSetMatcher(regexpRecord, singles, false, direction) 追加到 listOfMatchers。
  10. 如果 cs 包含空字符序列,则将 EmptyMatcher() 追加到 listOfMatchers。
  11. 令 m2 为 listOfMatchers 中最后一个 Matcher。
  12. 从倒数第二个元素开始反向迭代,对 listOfMatchers 的每个 Matcher m1,执行
    1. 将 m2 设置为 MatchTwoAlternatives(m1, m2)。
  13. 返回 m2。
AtomEscape :: k GroupName
  1. 令 matchingGroupSpecifiers 为 GroupSpecifiersThatMatch(GroupName)。
  2. 令 parenIndices 为新的空 List。
  3. 对 matchingGroupSpecifiers 的每个 GroupSpecifier groupSpecifier,执行
    1. 令 parenIndex 为 CountLeftCapturingParensBefore(groupSpecifier)。
    2. 将 parenIndex 追加到 parenIndices。
  4. 返回 BackreferenceMatcher(regexpRecord, parenIndices, direction)。

22.2.2.7.1 CharacterSetMatcher ( regexpRecord, charSet, invert, direction )

抽象操作 CharacterSetMatcher,接收参数 regexpRecord (RegExp 记录)、charSet (CharSet)、invert (Boolean) 和 direction ((forward 或 backward));返回值:Matcher。 调用时执行以下步骤:

  1. 如果 regexpRecord.[[UnicodeSets]] 是 true,则
    1. 断言:invert 是 false。
    2. 断言:charSet 的每个 CharSetElement 都由单个字符组成。
  2. 返回一个参数为 (x, c) 的新 Matcher,它捕获 regexpRecord、charSet、invert 和 direction,并在被调用时执行以下步骤:
    1. 断言:x 是 MatchState。
    2. 断言:c 是 MatcherContinuation。
    3. 令 input 为 x.[[Input]]。
    4. 令 endIndex 为 x.[[EndIndex]]。
    5. 如果 direction 是 forward,则令 f 为 endIndex + 1。
    6. 否则,令 f 为 endIndex - 1。
    7. 令 inputLength 为 input 中的元素数量。
    8. 如果 f < 0 或 f > inputLength,则返回 failure。
    9. 令 index 为 min(endIndex, f)。
    10. 令 char 为字符 input[index]。
    11. 令 cc 为 Canonicalize(regexpRecord, char)。
    12. 如果 charSet 中存在一个只包含一个字符 a 的 CharSetElement,且 Canonicalize(regexpRecord, a) 是 cc,则令 found 为 true;否则令 found 为 false。
    13. 如果 invert 是 false 且 found 是 false,则返回 failure。
    14. 如果 invert 是 true 且 found 是 true,则返回 failure。
    15. 令 capability 为 x.[[Captures]]。
    16. 令 y 为 MatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: capability }。
    17. 返回 c(y)。

22.2.2.7.2 BackreferenceMatcher ( regexpRecord, ns, direction )

抽象操作 BackreferenceMatcher,接收参数 regexpRecord (RegExp 记录)、ns (列表 (元素:正整数)) 和 direction ((forward 或 backward));返回值:Matcher。 调用时执行以下步骤:

  1. 返回一个参数为 (x, c) 的新 Matcher,它捕获 regexpRecord、ns 和 direction,并在被调用时执行以下步骤:
    1. 断言:x 是 MatchState。
    2. 断言:c 是 MatcherContinuation。
    3. 令 input 为 x.[[Input]]。
    4. 令 capability 为 x.[[Captures]]。
    5. 令 r 为 undefined。
    6. 对 ns 的每个整数 n,执行
      1. 如果 capability[n] 不是 undefined,则
        1. 断言:r 是 undefined。
        2. 将 r 设置为 capability[n]。
    7. 如果 r 是 undefined,则返回 c(x)。
    8. 令 endIndex 为 x.[[EndIndex]]。
    9. 令 rs 为 r.[[StartIndex]]。
    10. 令 re 为 r.[[EndIndex]]。
    11. 令 length 为 re - rs。
    12. 如果 direction 是 forward,则令 f 为 endIndex + length。
    13. 否则,令 f 为 endIndex - length。
    14. 令 inputLength 为 input 中的元素数量。
    15. 如果 f < 0 或 f > inputLength,则返回 failure。
    16. 令 g 为 min(endIndex, f)。
    17. 如果存在从 0(包含)到 length(不包含)区间内的整数 i,使得 Canonicalize(regexpRecord, input[rs + i]) 不是 Canonicalize(regexpRecord, input[g + i]),则返回 failure。
    18. 令 y 为 MatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: capability }。
    19. 返回 c(y)。

22.2.2.7.3 Canonicalize ( regexpRecord, char )

抽象操作 Canonicalize,接收参数 regexpRecord (RegExp 记录) 和 char (字符);返回值:字符。 调用时执行以下步骤:

  1. 如果 HasEitherUnicodeFlag(regexpRecord) 是 true 且 regexpRecord.[[IgnoreCase]] 是 true,则
    1. 如果 Unicode Character Database 的文件 CaseFolding.txt 为 char 提供了简单或通用大小写折叠映射,则返回将该映射应用于 char 的结果。
    2. 返回 char。
  2. 如果 regexpRecord.[[IgnoreCase]] 是 false,则返回 char。
  3. 断言:char 是 UTF-16 码元。
  4. 令 codePoint 为数值等于 char 数值的码点。
  5. 令 mappedCodePoints 为根据 Unicode Default Case Conversion 算法的 toUppercase(« codePoint »)。
  6. 如果 CodePointsToString(mappedCodePoints) 的长度 ≠ 1,则返回 char。
  7. 断言:mappedCodePoints 中的元素数量为 1。
  8. 令 mappedCodePoint 为 mappedCodePoints 中唯一的码点元素。
  9. 如果 char 的数值 ≥ 128 且 mappedCodePoint 的数值 < 128,则返回 char。
  10. 返回数值等于 mappedCodePoint 数值的码元。
注

在 HasEitherUnicodeFlag(regexpRecord) 是 true 的不区分大小写匹配中,所有字符在比较之前都会隐式使用 Unicode 标准提供的简单映射进行大小写折叠。简单映射始终映射到单个码点,因此例如不会将 ß (U+00DF LATIN SMALL LETTER SHARP S) 映射为 ss 或 SS。不过,它可以将 Basic Latin 块之外的码点映射到其中的码点——例如,ſ (U+017F LATIN SMALL LETTER LONG S) 大小写折叠为 s (U+0073 LATIN SMALL LETTER S),而 K (U+212A KELVIN SIGN) 大小写折叠为 k (U+006B LATIN SMALL LETTER K)。包含这些码点的 Strings 会被 /[a-z]/ui 等正则表达式匹配。

在 HasEitherUnicodeFlag(regexpRecord) 是 false 的不区分大小写匹配中,映射基于 Unicode Default Case Conversion 算法 toUppercase,而不是 toCasefold,这会产生一些细微差异。例如,Ω (U+2126 OHM SIGN) 由 toUppercase 映射为自身,但由 toCasefold 与 Ω (U+03A9 GREEK CAPITAL LETTER OMEGA) 一起映射为 ω (U+03C9 GREEK SMALL LETTER OMEGA),因此 "\u2126" 会被 /[ω]/ui 和 /[\u03A9]/ui 匹配,但不会被 /[ω]/i 或 /[\u03A9]/i 匹配。此外,Basic Latin 块之外的码点不会映射到其中的码点,因此 "\u017F ſ" 和 "\u212A K" 等字符串不会被 /[a-z]/i 匹配。

22.2.2.7.4 UpdateModifiers ( regexpRecord, add, remove )

抽象操作 UpdateModifiers,接收参数 regexpRecord (RegExp 记录)、add (String) 和 remove (String);返回值:RegExp 记录。 调用时执行以下步骤:

  1. 断言:add 和 remove 没有共同元素。
  2. 令 ignoreCase 为 regexpRecord.[[IgnoreCase]]。
  3. 令 multiline 为 regexpRecord.[[Multiline]]。
  4. 令 dotAll 为 regexpRecord.[[DotAll]]。
  5. 令 unicode 为 regexpRecord.[[Unicode]]。
  6. 令 unicodeSets 为 regexpRecord.[[UnicodeSets]]。
  7. 令 capturingGroupsCount 为 regexpRecord.[[CapturingGroupsCount]]。
  8. 如果 remove 包含 "i",则将 ignoreCase 设置为 false。
  9. 否则如果 add 包含 "i",则将 ignoreCase 设置为 true。
  10. 如果 remove 包含 "m",则将 multiline 设置为 false。
  11. 否则如果 add 包含 "m",则将 multiline 设置为 true。
  12. 如果 remove 包含 "s",则将 dotAll 设置为 false。
  13. 否则如果 add 包含 "s",则将 dotAll 设置为 true。
  14. 返回 RegExp Record { [[IgnoreCase]]: ignoreCase, [[Multiline]]: multiline, [[DotAll]]: dotAll, [[Unicode]]: unicode, [[UnicodeSets]]: unicodeSets, [[CapturingGroupsCount]]: capturingGroupsCount }。

22.2.2.8 Runtime Semantics: CompileCharacterClass

语法制导操作 CompileCharacterClass,接收参数 regexpRecord (RegExp 记录);返回值:记录 (字段:[[CharSet]] (CharSet), [[Invert]] (Boolean))。 它按以下产生式分别定义:

CharacterClass :: [ ClassContents ]
  1. 令 charSet 为 CompileToCharSet of ClassContents with argument regexpRecord。
  2. 返回 Record { [[CharSet]]: charSet, [[Invert]]: false }。
CharacterClass :: [^ ClassContents ]
  1. 令 charSet 为 CompileToCharSet of ClassContents with argument regexpRecord。
  2. 如果 regexpRecord.[[UnicodeSets]] 是 true,则
    1. 返回 Record { [[CharSet]]: CharacterComplement(regexpRecord, charSet), [[Invert]]: false }。
  3. 返回 Record { [[CharSet]]: charSet, [[Invert]]: true }。

22.2.2.9 Runtime Semantics: CompileToCharSet

语法制导操作 CompileToCharSet,接收参数 regexpRecord (RegExp 记录);返回值:CharSet。

注 1

本节在 B.1.2.8 中进行了修订。

它按以下产生式分别定义:

ClassContents :: [empty]
  1. 返回空 CharSet。
NonemptyClassRanges :: ClassAtom NonemptyClassRangesNoDash
  1. 令 charSet 为 CompileToCharSet of ClassAtom with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of NonemptyClassRangesNoDash with argument regexpRecord。
  3. 返回 CharSet charSet 和 otherSet 的并集。
NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. 令 charSet 为 CompileToCharSet of the first ClassAtom with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of the second ClassAtom with argument regexpRecord。
  3. 令 remainingSet 为 CompileToCharSet of ClassContents with argument regexpRecord。
  4. 令 rangeSet 为 CharacterRange(charSet, otherSet)。
  5. 返回 rangeSet 和 remainingSet 的并集。
NonemptyClassRangesNoDash :: ClassAtomNoDash NonemptyClassRangesNoDash
  1. 令 charSet 为 CompileToCharSet of ClassAtomNoDash with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of NonemptyClassRangesNoDash with argument regexpRecord。
  3. 返回 CharSet charSet 和 otherSet 的并集。
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. 令 charSet 为 CompileToCharSet of ClassAtomNoDash with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of ClassAtom with argument regexpRecord。
  3. 令 remainingSet 为 CompileToCharSet of ClassContents with argument regexpRecord。
  4. 令 rangeSet 为 CharacterRange(charSet, otherSet)。
  5. 返回 rangeSet 和 remainingSet 的并集。
注 2

ClassContents 可以展开为单个 ClassAtom 和/或由连字符分隔的两个 ClassAtom 的范围。在后一种情况下,ClassContents 包括第一个 ClassAtom 与第二个 ClassAtom 之间(包含两端)的所有字符;如果任一 ClassAtom 不表示单个字符(例如其中一个是 \w),或者第一个 ClassAtom 的字符值严格大于第二个 ClassAtom 的字符值,则发生错误。

注 3

即使模式忽略大小写,范围两端的大小写仍会影响哪些字符属于该范围。因此,例如,模式 /[E-F]/i 只匹配字母 E、F、e 和 f,而模式 /[E-f]/i 会匹配 Unicode Basic Latin 块中的所有大写和小写字母,以及符号 [、\、]、^、_ 和 `。

注 4

- 字符可以按字面处理,也可以表示范围。如果它是 ClassContents 的第一个或最后一个字符、范围规范的开始或结束边界,或者紧跟在范围规范之后,则按字面处理。

ClassAtom :: -
  1. 返回包含单个字符 - U+002D (HYPHEN-MINUS) 的 CharSet。
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. 返回包含 SourceCharacter 所匹配字符的 CharSet。
ClassEscape :: b - CharacterEscape
  1. 令 charValue 为 CharacterValue of this ClassEscape。
  2. 令 char 为字符值等于 charValue 的字符。
  3. 返回包含单个字符 char 的 CharSet。
注 5

ClassAtom 可以使用正则表达式其余部分允许的任何转义序列,但 \b、\B 和反向引用除外。在 CharacterClass 内,\b 表示退格字符,而 \B 和反向引用会引发错误。在 ClassAtom 内使用反向引用会导致错误。

CharacterClassEscape :: d
  1. 返回包含字符 0、1、2、3、4、5、6、7、8 和 9 的十元素 CharSet。
CharacterClassEscape :: D
  1. 令 charSet 为由 CharacterClassEscape :: d 返回的 CharSet。
  2. 返回 CharacterComplement(regexpRecord, charSet)。
CharacterClassEscape :: s
  1. 返回包含与 WhiteSpace 或 LineTerminator 产生式右侧码点对应的所有字符的 CharSet。
CharacterClassEscape :: S
  1. 令 charSet 为由 CharacterClassEscape :: s 返回的 CharSet。
  2. 返回 CharacterComplement(regexpRecord, charSet)。
CharacterClassEscape :: w
  1. 返回 MaybeSimpleCaseFolding(regexpRecord, WordCharacters(regexpRecord))。
CharacterClassEscape :: W
  1. 令 charSet 为由 CharacterClassEscape :: w 返回的 CharSet。
  2. 返回 CharacterComplement(regexpRecord, charSet)。
CharacterClassEscape :: p{ UnicodePropertyValueExpression }
  1. 返回 CompileToCharSet of UnicodePropertyValueExpression with argument regexpRecord。
CharacterClassEscape :: P{ UnicodePropertyValueExpression }
  1. 令 charSet 为 CompileToCharSet of UnicodePropertyValueExpression with argument regexpRecord。
  2. 断言:charSet 只包含单个码点。
  3. 返回 CharacterComplement(regexpRecord, charSet)。
UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  1. 令 ps 为 UnicodePropertyName 所匹配的源文本。
  2. 令 p 为 UnicodeMatchProperty(regexpRecord, ps)。
  3. 断言:p 是 表 65 的“Property name and aliases”列中列出的Unicode 属性名称或属性别名。
  4. 令 vs 为 UnicodePropertyValue 所匹配的源文本。
  5. 令 v 为 UnicodeMatchPropertyValue(p, vs)。
  6. 令 charSet 为包含所有其字符数据库定义中属性 p 的值为 v 的 Unicode 码点的 CharSet。
  7. 返回 MaybeSimpleCaseFolding(regexpRecord, charSet)。
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. 令 s 为 LoneUnicodePropertyNameOrValue 所匹配的源文本。
  2. 如果 UnicodeMatchPropertyValue(General_Category, s) 是 PropertyValueAliases.txt 中为 General_Category (gc) 属性列出的 Unicode 属性值或属性值别名,则
    1. 返回包含所有其字符数据库定义中属性“General_Category”的值为 s 的 Unicode 码点的 CharSet。
  3. 令 p 为 UnicodeMatchProperty(regexpRecord, s)。
  4. 断言:p 是 表 66 的“Property name and aliases”列中列出的二元 Unicode 属性或二元属性别名,或者是 表 67 的“Property name”列中列出的字符串二元 Unicode 属性。
  5. 令 charSet 为包含所有其字符数据库定义中属性 p 的值为“True”的 CharSetElement 的 CharSet。
  6. 返回 MaybeSimpleCaseFolding(regexpRecord, charSet)。
ClassUnion :: ClassSetRange ClassUnionopt
  1. 令 charSet 为 CompileToCharSet of ClassSetRange with argument regexpRecord。
  2. 如果存在 ClassUnion,则
    1. 令 otherSet 为 CompileToCharSet of ClassUnion with argument regexpRecord。
    2. 返回 CharSet charSet 和 otherSet 的并集。
  3. 返回 charSet。
ClassUnion :: ClassSetOperand ClassUnionopt
  1. 令 charSet 为 CompileToCharSet of ClassSetOperand with argument regexpRecord。
  2. 如果存在 ClassUnion,则
    1. 令 otherSet 为 CompileToCharSet of ClassUnion with argument regexpRecord。
    2. 返回 CharSet charSet 和 otherSet 的并集。
  3. 返回 charSet。
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. 令 charSet 为 CompileToCharSet of the first ClassSetOperand with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of the second ClassSetOperand with argument regexpRecord。
  3. 返回 CharSet charSet 和 otherSet 的交集。
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. 令 charSet 为 CompileToCharSet of the ClassIntersection with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of the ClassSetOperand with argument regexpRecord。
  3. 返回 CharSet charSet 和 otherSet 的交集。
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. 令 charSet 为 CompileToCharSet of the first ClassSetOperand with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of the second ClassSetOperand with argument regexpRecord。
  3. 返回包含 charSet 中不同时也是 otherSet 的 CharSetElement 的所有 CharSetElement 的 CharSet。
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. 令 charSet 为 CompileToCharSet of the ClassSubtraction with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of the ClassSetOperand with argument regexpRecord。
  3. 返回包含 charSet 中不同时也是 otherSet 的 CharSetElement 的所有 CharSetElement 的 CharSet。
ClassSetRange :: ClassSetCharacter - ClassSetCharacter
  1. 令 charSet 为 CompileToCharSet of the first ClassSetCharacter with argument regexpRecord。
  2. 令 otherSet 为 CompileToCharSet of the second ClassSetCharacter with argument regexpRecord。
  3. 返回 MaybeSimpleCaseFolding(regexpRecord, CharacterRange(charSet, otherSet))。
注 6

结果通常会由两个或更多范围组成。当 UnicodeSets 是 true 且 IgnoreCase 是 true 时,MaybeSimpleCaseFolding(regexpRecord, [Ā-č]) 将只包含该范围内编号为奇数的码点。

ClassSetOperand :: ClassSetCharacter
  1. 令 charSet 为 CompileToCharSet of ClassSetCharacter with argument regexpRecord。
  2. 返回 MaybeSimpleCaseFolding(regexpRecord, charSet)。
ClassSetOperand :: ClassStringDisjunction
  1. 令 charSet 为 CompileToCharSet of ClassStringDisjunction with argument regexpRecord。
  2. 返回 MaybeSimpleCaseFolding(regexpRecord, charSet)。
ClassSetOperand :: NestedClass
  1. 返回 CompileToCharSet of NestedClass with argument regexpRecord。
NestedClass :: [ ClassContents ]
  1. 返回 CompileToCharSet of ClassContents with argument regexpRecord。
NestedClass :: [^ ClassContents ]
  1. 令 charSet 为 CompileToCharSet of ClassContents with argument regexpRecord。
  2. 返回 CharacterComplement(regexpRecord, charSet)。
NestedClass :: \ CharacterClassEscape
  1. 返回 CompileToCharSet of CharacterClassEscape with argument regexpRecord。
ClassStringDisjunction :: \q{ ClassStringDisjunctionContents }
  1. 返回 CompileToCharSet of ClassStringDisjunctionContents with argument regexpRecord。
ClassStringDisjunctionContents :: ClassString
  1. 令 s 为 CompileClassSetString of ClassString with argument regexpRecord。
  2. 返回包含唯一字符串 s 的 CharSet。
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. 令 s 为 CompileClassSetString of ClassString with argument regexpRecord。
  2. 令 charSet 为包含唯一字符串 s 的 CharSet。
  3. 令 otherSet 为 CompileToCharSet of ClassStringDisjunctionContents with argument regexpRecord。
  4. 返回 CharSet charSet 和 otherSet 的并集。
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape \ ClassSetReservedPunctuator
  1. 令 charValue 为 CharacterValue of this ClassSetCharacter。
  2. 令 char 为字符值等于 charValue 的字符。
  3. 返回包含单个字符 char 的 CharSet。
ClassSetCharacter :: \b
  1. 返回包含单个字符 U+0008 (BACKSPACE) 的 CharSet。

22.2.2.9.1 CharacterRange ( charSet, otherSet )

抽象操作 CharacterRange,接收参数 charSet (CharSet) 和 otherSet (CharSet);返回值:CharSet。 调用时执行以下步骤:

  1. 断言:charSet 和 otherSet 各自恰好包含一个字符。
  2. 令 a 为 CharSet charSet 中的唯一字符。
  3. 令 b 为 CharSet otherSet 中的唯一字符。
  4. 令 i 为字符 a 的字符值。
  5. 令 j 为字符 b 的字符值。
  6. 断言:i ≤ j。
  7. 返回包含字符值位于从 i 到 j 闭区间内的所有字符的 CharSet。

22.2.2.9.2 HasEitherUnicodeFlag ( regexpRecord )

抽象操作 HasEitherUnicodeFlag,接收参数 regexpRecord (RegExp 记录);返回值:Boolean。 调用时执行以下步骤:

  1. 如果 regexpRecord.[[Unicode]] 是 true 或 regexpRecord.[[UnicodeSets]] 是 true,则返回 true。
  2. 返回 false。

22.2.2.9.3 WordCharacters ( regexpRecord )

抽象操作 WordCharacters,接收参数 regexpRecord (RegExp 记录);返回值:CharSet。 返回一个 CharSet,其中包含为了 \b、\B、\w 和 \W 而被视为“单词字符”的字符。 调用时执行以下步骤:

  1. 令 basicWordChars 为包含 ASCII 单词字符中每个字符的 CharSet。
  2. 令 extraWordChars 为包含所有满足以下条件的字符 c 的 CharSet:c 不在 basicWordChars 中,但 Canonicalize(regexpRecord, c) 在 basicWordChars 中。
  3. 断言:除非 HasEitherUnicodeFlag(regexpRecord) 是 true 且 regexpRecord.[[IgnoreCase]] 是 true,否则 extraWordChars 为空。
  4. 返回 basicWordChars 和 extraWordChars 的并集。

22.2.2.9.4 AllCharacters ( regexpRecord )

抽象操作 AllCharacters,接收参数 regexpRecord (RegExp 记录);返回值:CharSet。 根据正则表达式标志返回“所有字符”的集合。 调用时执行以下步骤:

  1. 如果 regexpRecord.[[UnicodeSets]] 是 true 且 regexpRecord.[[IgnoreCase]] 是 true,则
    1. 返回包含所有没有 Simple Case Folding 映射(即 scf(c)=c)的 Unicode 码点 c 的 CharSet。
  2. 如果 HasEitherUnicodeFlag(regexpRecord) 是 true,则
    1. 返回包含所有码点值的 CharSet。
  3. 返回包含所有码元值的 CharSet。

22.2.2.9.5 MaybeSimpleCaseFolding ( regexpRecord, charSet )

抽象操作 MaybeSimpleCaseFolding,接收参数 regexpRecord (RegExp 记录) 和 charSet (CharSet);返回值:CharSet。 如果 regexpRecord.[[UnicodeSets]] 是 false 或 regexpRecord.[[IgnoreCase]] 是 false,则返回 charSet。否则,它使用 Unicode Character Database 的文件 CaseFolding.txt 中的 Simple Case Folding(scf(codePoint))定义(每个定义都将单个码点映射到另一个单个码点),逐字符地将 charSet 的每个 CharSetElement 映射为规范形式,并返回所得 CharSet。 调用时执行以下步骤:

  1. 如果 regexpRecord.[[UnicodeSets]] 是 false 或 regexpRecord.[[IgnoreCase]] 是 false,则返回 charSet。
  2. 令 otherSet 为新的空 CharSet。
  3. 对 charSet 的每个 CharSetElement s,执行
    1. 令 t 为空字符序列。
    2. 对 s 的每个单一码点 codePoint,执行
      1. 将 scf(codePoint) 追加到 t。
    3. 将 t 添加到 otherSet。
  4. 返回 otherSet。

22.2.2.9.6 CharacterComplement ( regexpRecord, complement )

抽象操作 CharacterComplement,接收参数 regexpRecord (RegExp 记录) 和 complement (CharSet);返回值:CharSet。 调用时执行以下步骤:

  1. 令 charSet 为 AllCharacters(regexpRecord)。
  2. 返回包含 charSet 中不同时也是 complement 的 CharSetElement 的所有 CharSetElement 的 CharSet。

22.2.2.9.7 UnicodeMatchProperty ( regexpRecord, p )

抽象操作 UnicodeMatchProperty,接收参数 regexpRecord (RegExp 记录) 和 p (ECMAScript 源文本);返回值:a Unicode property name。 调用时执行以下步骤:

  1. 如果 regexpRecord.[[UnicodeSets]] 是 true,并且 p 是 表 67 的“Property name”列中列出的Unicode 属性名称,则
    1. 返回 Unicode 码点 List p。
  2. 断言:p 是 表 65 或 表 66 的“Property name and aliases”列中列出的Unicode 属性名称或属性别名。
  3. 令 c 为相应行的“Canonical property name”列中给出的 p 的规范属性名称。
  4. 返回 Unicode 码点 List c。

实现必须支持 表 65、表 66 和 表 67 中列出的Unicode 属性名称和别名。为确保互操作性,实现不得支持任何其他属性名称或别名。

注 1

例如,Script_Extensions(属性名称)和 scx(属性别名)有效,但 script_extensions 或 Scx 无效。

注 2

列出的属性构成 UTS18 RL1.2 所要求内容的超集。

注 3

这些表中条目的拼写(包括大小写)与 Unicode Character Database 中 PropertyAliases.txt 文件使用的拼写一致。该文件中的精确拼写保证保持稳定。

表 65: Non-binary Unicode property aliases and their canonical property names
Property name and aliases Canonical property name
General_Category General_Category
gc
Script Script
sc
Script_Extensions Script_Extensions
scx
表 66: Binary Unicode property aliases and their canonical property names
Property name and aliases Canonical property name
ASCII ASCII
ASCII_Hex_Digit ASCII_Hex_Digit
AHex
Alphabetic Alphabetic
Alpha
Any Any
Assigned Assigned
Bidi_Control Bidi_Control
Bidi_C
Bidi_Mirrored Bidi_Mirrored
Bidi_M
Case_Ignorable Case_Ignorable
CI
Cased Cased
Changes_When_Casefolded Changes_When_Casefolded
CWCF
Changes_When_Casemapped Changes_When_Casemapped
CWCM
Changes_When_Lowercased Changes_When_Lowercased
CWL
Changes_When_NFKC_Casefolded Changes_When_NFKC_Casefolded
CWKCF
Changes_When_Titlecased Changes_When_Titlecased
CWT
Changes_When_Uppercased Changes_When_Uppercased
CWU
Dash Dash
Default_Ignorable_Code_Point Default_Ignorable_Code_Point
DI
Deprecated Deprecated
Dep
Diacritic Diacritic
Dia
Emoji Emoji
Emoji_Component Emoji_Component
EComp
Emoji_Modifier Emoji_Modifier
EMod
Emoji_Modifier_Base Emoji_Modifier_Base
EBase
Emoji_Presentation Emoji_Presentation
EPres
Extended_Pictographic Extended_Pictographic
ExtPict
Extender Extender
Ext
Grapheme_Base Grapheme_Base
Gr_Base
Grapheme_Extend Grapheme_Extend
Gr_Ext
Hex_Digit Hex_Digit
Hex
IDS_Binary_Operator IDS_Binary_Operator
IDSB
IDS_Trinary_Operator IDS_Trinary_Operator
IDST
ID_Continue ID_Continue
IDC
ID_Start ID_Start
IDS
Ideographic Ideographic
Ideo
Join_Control Join_Control
Join_C
Logical_Order_Exception Logical_Order_Exception
LOE
Lowercase Lowercase
Lower
Math Math
Noncharacter_Code_Point Noncharacter_Code_Point
NChar
Pattern_Syntax Pattern_Syntax
Pat_Syn
Pattern_White_Space Pattern_White_Space
Pat_WS
Quotation_Mark Quotation_Mark
QMark
Radical Radical
Regional_Indicator Regional_Indicator
RI
Sentence_Terminal Sentence_Terminal
STerm
Soft_Dotted Soft_Dotted
SD
Terminal_Punctuation Terminal_Punctuation
Term
Unified_Ideograph Unified_Ideograph
UIdeo
Uppercase Uppercase
Upper
Variation_Selector Variation_Selector
VS
White_Space White_Space
space
XID_Continue XID_Continue
XIDC
XID_Start XID_Start
XIDS
表 67: Binary Unicode properties of strings
Property name
Basic_Emoji
Emoji_Keycap_Sequence
RGI_Emoji_Modifier_Sequence
RGI_Emoji_Flag_Sequence
RGI_Emoji_Tag_Sequence
RGI_Emoji_ZWJ_Sequence
RGI_Emoji

22.2.2.9.8 UnicodeMatchPropertyValue ( p, v )

抽象操作 UnicodeMatchPropertyValue,接收参数 p (ECMAScript 源文本) 和 v (ECMAScript 源文本);返回值:a Unicode property value。 调用时执行以下步骤:

  1. 断言:p 是 表 65 的“Canonical property name”列中列出的规范、无别名的Unicode 属性名称。
  2. 断言:v 是 PropertyValueAliases.txt 中为 Unicode 属性 p 列出的属性值或属性值别名。
  3. 令 value 为相应行的“Canonical property value”列中给出的 v 的规范属性值。
  4. 返回 Unicode 码点 List value。

实现必须支持 PropertyValueAliases.txt 中为 表 65 所列属性提供的 Unicode 属性值和属性值别名。为确保互操作性,实现不得支持任何其他属性值或属性值别名。

注 1

例如,Xpeo 和 Old_Persian 是有效的 Script_Extensions 值,但 xpeo 和 Old Persian 无效。

注 2

此算法与 UAX44 中列出的符号值匹配规则不同:不会忽略大小写、空白、U+002D (HYPHEN-MINUS) 和 U+005F (LOW LINE),并且不支持 Is 前缀。

22.2.2.10 Runtime Semantics: CompileClassSetString

语法制导操作 CompileClassSetString,接收参数 regexpRecord (RegExp 记录);返回值:a sequence of characters。 它按以下产生式分别定义:

ClassString :: [empty]
  1. 返回空字符序列。
ClassString :: NonEmptyClassString
  1. 返回 CompileClassSetString of NonEmptyClassString with argument regexpRecord。
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. 令 cs 为 CompileToCharSet of ClassSetCharacter with argument regexpRecord。
  2. 令 s1 为 cs 中唯一 CharSetElement 所组成的字符序列。
  3. 如果存在 NonEmptyClassString,则
    1. 令 s2 为 CompileClassSetString of NonEmptyClassString with argument regexpRecord。
    2. 返回 s1 和 s2 的连接。
  4. 返回 s1。

22.2.3 RegExp 创建的抽象操作

22.2.3.1 RegExpCreate ( pattern, flags )

抽象操作 RegExpCreate,接收参数 pattern (ECMAScript 语言值) 和 flags ((String 或 undefined));返回值:(正常完成 (值:Object) 或 抛出完成)。 调用时执行以下步骤:

  1. 令 obj 为 ! RegExpAlloc(%RegExp%)。
  2. 返回 ? RegExpInitialize(obj, pattern, flags)。

22.2.3.2 RegExpAlloc ( newTarget )

抽象操作 RegExpAlloc,接收参数 newTarget (构造函数);返回值:(正常完成 (值:Object) 或 抛出完成)。 调用时执行以下步骤:

  1. 令 obj 为 ? OrdinaryCreateFromConstructor(newTarget, "%RegExp.prototype%", « [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], [[RegExpMatcher]] »)。
  2. 执行 ! DefinePropertyOrThrow(obj, "lastIndex", PropertyDescriptor { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  3. 返回 obj。

22.2.3.3 RegExpInitialize ( obj, pattern, flags )

抽象操作 RegExpInitialize,接收参数 obj (Object)、pattern (ECMAScript 语言值) 和 flags (ECMAScript 语言值);返回值:(正常完成 (值:Object) 或 抛出完成)。 调用时执行以下步骤:

  1. 如果 pattern 是 undefined,则将 pattern 设置为空 String。
  2. 否则,将 pattern 设置为 ? ToString(pattern)。
  3. 如果 flags 是 undefined,则将 flags 设置为空 String。
  4. 否则,将 flags 设置为 ? ToString(flags)。
  5. 如果 flags 包含除 "d"、"g"、"i"、"m"、"s"、"u"、"v" 或 "y" 之外的任何码元,则抛出 SyntaxError 异常。
  6. 如果 flags 多次包含任何码元,则抛出 SyntaxError 异常。
  7. 如果 flags 包含 "i",则令 i 为 true;否则令 i 为 false。
  8. 如果 flags 包含 "m",则令 m 为 true;否则令 m 为 false。
  9. 如果 flags 包含 "s",则令 s 为 true;否则令 s 为 false。
  10. 如果 flags 包含 "u",则令 u 为 true;否则令 u 为 false。
  11. 如果 flags 包含 "v",则令 v 为 true;否则令 v 为 false。
  12. 如果 u 是 true 或 v 是 true,则
    1. 令 patternText 为 StringToCodePoints(pattern)。
  13. 否则,
    1. 令 patternText 为将 pattern 的每个 16 位元素解释为 Unicode BMP 码点所得的结果。不会对这些元素应用 UTF-16 解码。
  14. 令 parseResult 为 ParsePattern(patternText, u, v)。
  15. 如果 parseResult 是非空的 SyntaxError 对象 List,则抛出 SyntaxError 异常。
  16. 断言:parseResult 是 Pattern Parse Node。
  17. 将 obj.[[OriginalSource]] 设置为 pattern。
  18. 将 obj.[[OriginalFlags]] 设置为 flags。
  19. 令 capturingGroupsCount 为 CountLeftCapturingParensWithin(parseResult)。
  20. 令 regexpRecord 为 RegExp Record { [[IgnoreCase]]: i, [[Multiline]]: m, [[DotAll]]: s, [[Unicode]]: u, [[UnicodeSets]]: v, [[CapturingGroupsCount]]: capturingGroupsCount }。
  21. 将 obj.[[RegExpRecord]] 设置为 regexpRecord。
  22. 将 obj.[[RegExpMatcher]] 设置为 CompilePattern of parseResult with argument regexpRecord。
  23. 执行 ? Set(obj, "lastIndex", +0𝔽, true)。
  24. 返回 obj。

22.2.3.4 Static Semantics: ParsePattern ( patternText, u, v )

抽象操作 ParsePattern,接收参数 patternText (a sequence of Unicode code points)、u (Boolean) 和 v (Boolean);返回值:(解析节点 或 a non-empty List of SyntaxError objects)。

注

本节在 B.1.2.9 中进行了修订。

调用时执行以下步骤:

  1. 如果 v 是 true 且 u 是 true,则
    1. 令 parseResult 为包含一个或多个 SyntaxError 对象的 List。
  2. 否则如果 v 是 true,则
    1. 令 parseResult 为 ParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups])。
  3. 否则如果 u 是 true,则
    1. 令 parseResult 为 ParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])。
  4. 否则,
    1. 令 parseResult 为 ParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])。
  5. 返回 parseResult。

22.2.4 RegExp 构造函数

RegExp 构造函数:

  • 是 %RegExp%。
  • 是全局对象的 "RegExp" 属性的初始值。
  • 作为构造函数调用时,创建并初始化新的 RegExp 对象。
  • 作为函数而不是构造函数调用时,要么返回新的 RegExp 对象,要么如果唯一参数是 RegExp 对象,则返回该参数本身。
  • 可以用作类定义的 extends 子句的值。希望继承指定 RegExp 行为的子类构造函数必须包含对 RegExp 构造函数的 super 调用,以创建并初始化具有必要内部槽的子类实例。

22.2.4.1 RegExp ( patternOrRegexp, flags )

调用时,此函数执行以下步骤:

  1. 令 patternIsRegExp 为 ? IsRegExp(patternOrRegexp)。
  2. 如果 NewTarget 是 undefined,则
    1. 令 newTarget 为活动函数对象。
    2. 如果 patternIsRegExp 是 true 且 flags 是 undefined,则
      1. 令 patternCtor 为 ? Get(patternOrRegexp, "constructor")。
      2. 如果 SameValue(newTarget, patternCtor) 是 true,则返回 patternOrRegexp。
  3. 否则,
    1. 令 newTarget 为 NewTarget。
  4. 如果 patternOrRegexp 是 Object 且 patternOrRegexp 具有 [[RegExpMatcher]] 内部槽,则
    1. 令 patternSource 为 patternOrRegexp.[[OriginalSource]]。
    2. 如果 flags 是 undefined,则将 flags 设置为 patternOrRegexp.[[OriginalFlags]]。
  5. 否则如果 patternIsRegExp 是 true,则
    1. 令 patternSource 为 ? Get(patternOrRegexp, "source")。
    2. 如果 flags 是 undefined,则
      1. 将 flags 设置为 ? Get(patternOrRegexp, "flags")。
  6. 否则,
    1. 令 patternSource 为 patternOrRegexp。
  7. 令 obj 为 ? RegExpAlloc(newTarget)。
  8. 返回 ? RegExpInitialize(obj, patternSource, flags)。
注

如果使用 StringLiteral 提供 pattern,则在该 String 被此函数处理之前会执行通常的转义序列替换。如果 pattern 必须包含此函数要识别的转义序列,则任何 U+005C (REVERSE SOLIDUS) 码点都必须在 StringLiteral 中进行转义,以防止它们在形成 StringLiteral 内容时被移除。

22.2.5 RegExp 构造函数的属性

RegExp 构造函数:

22.2.5.1 RegExp.escape ( string )

此函数返回 string 的副本,其中在正则表达式 Pattern 中可能具有特殊含义的字符被替换为等价的转义序列。

调用时,它执行以下步骤:

  1. 如果 string 不是 String,则抛出 TypeError 异常。
  2. 令 escaped 为空 String。
  3. 令 codePointList 为 StringToCodePoints(string)。
  4. 对 codePointList 的每个码点 codePoint,执行
    1. 如果 escaped 是空 String,且 codePoint 被 DecimalDigit 或 AsciiLetter 匹配,则
      1. 注:对前导数字进行转义可确保输出与可能用于 \0 字符转义或 \1 等 DecimalEscape 之后的模式文本相对应,并且仍匹配 string,而不是被解释为前一个转义序列的扩展。对前导 ASCII 字母进行转义,在 \c 之后的上下文中具有相同作用。
      2. 令 numericValue 为 codePoint 的数值。
      3. 令 hex 为 Number::toString(𝔽(numericValue), 16)。
      4. 断言:hex 的长度为 2。
      5. 将 escaped 设置为码元 0x005C (REVERSE SOLIDUS)、"x" 和 hex 的字符串连接。
    2. 否则,
      1. 将 escaped 设置为 escaped 和 EncodeForRegExpEscape(codePoint) 的字符串连接。
  5. 返回 escaped。
注

尽管名称相似,EscapeRegExpPattern 和 RegExp.escape 执行的操作并不相似。前者转义模式以便表示为字符串,而此函数转义字符串以便在模式内部表示。

22.2.5.1.1 EncodeForRegExpEscape ( codePoint )

抽象操作 EncodeForRegExpEscape,接收参数 codePoint (码点);返回值:String。 它返回一个表示用于匹配 codePoint 的 Pattern 的 String。如果 codePoint 是空白或 ASCII 标点符号,则返回值是转义序列。否则,返回值是 codePoint 本身的 String 表示。 调用时执行以下步骤:

  1. 如果 codePoint 被 SyntaxCharacter 匹配,或者 codePoint 是 U+002F (SOLIDUS),则
    1. 返回 0x005C (REVERSE SOLIDUS) 和 UTF16EncodeCodePoint(codePoint) 的字符串连接。
  2. 如果 codePoint 是 表 63 的“Code Point”列中列出的码点,则
    1. 返回 0x005C (REVERSE SOLIDUS) 与该表中“Code Point”列包含 codePoint 的行的“ControlEscape”列中的字符串的字符串连接。
  3. 令 otherPunctuators 为 ",-=<>#&!%:;@~'`" 与码元 0x0022 (QUOTATION MARK) 的字符串连接。
  4. 令 toEscape 为 StringToCodePoints(otherPunctuators)。
  5. 如果 toEscape 包含 codePoint、codePoint 被 WhiteSpace 或 LineTerminator 匹配,或者 codePoint 的数值与前导代理项或尾随代理项相同,则
    1. 令 codePointNumber 为 codePoint 的数值。
    2. 如果 codePointNumber ≤ 0xFF,则
      1. 令 hex 为 Number::toString(𝔽(codePointNumber), 16)。
      2. 返回码元 0x005C (REVERSE SOLIDUS)、"x" 和 StringPad(hex, 2, "0", start) 的字符串连接。
    3. 令 escaped 为空 String。
    4. 令 codeUnits 为 UTF16EncodeCodePoint(codePoint)。
    5. 对 codeUnits 的每个码元 codeUnit,执行
      1. 将 escaped 设置为 escaped 和 UnicodeEscape(codeUnit) 的字符串连接。
    6. 返回 escaped。
  6. 返回 UTF16EncodeCodePoint(codePoint)。

22.2.5.2 RegExp.prototype

RegExp.prototype 的初始值是 RegExp 原型对象。

此属性具有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }。

22.2.5.3 get RegExp [ %Symbol.species% ]

RegExp[%Symbol.species%] 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 返回 this value。

此函数的 "name" 属性值是 "get [Symbol.species]"。

注

RegExp 原型方法通常使用其 this value 的构造函数创建派生对象。不过,子类构造函数可以通过重新定义其 %Symbol.species% 属性来覆盖该默认行为。

22.2.6 RegExp 原型对象的属性

RegExp 原型对象:

  • 是 %RegExp.prototype%。
  • 是普通对象。
  • 不是 RegExp 实例,并且没有 [[RegExpMatcher]] 内部槽或 RegExp 实例对象的任何其他内部槽。
  • 具有 [[Prototype]] 内部槽,其值是 %Object.prototype%。
注

RegExp 原型对象没有自己的 "valueOf" 属性;不过,它从 Object 原型对象继承 "valueOf" 属性。

22.2.6.1 RegExp.prototype.constructor

RegExp.prototype.constructor 的初始值是 %RegExp%。

22.2.6.2 RegExp.prototype.exec ( string )

此方法在 string 中搜索正则表达式模式的出现位置,并返回包含匹配结果的 Array;如果 string 没有匹配,则返回 null。

调用时,它执行以下步骤:

  1. 令 regexp 为 this value。
  2. 执行 ? RequireInternalSlot(regexp, [[RegExpMatcher]])。
  3. 将 string 设置为 ? ToString(string)。
  4. 返回 ? RegExpBuiltinExec(regexp, string)。

22.2.6.3 get RegExp.prototype.dotAll

RegExp.prototype.dotAll 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 令 codeUnit 为码元 0x0073 (LATIN SMALL LETTER S)。
  3. 返回 ? RegExpHasFlag(regexp, codeUnit)。

22.2.6.4 get RegExp.prototype.flags

RegExp.prototype.flags 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 令 codeUnits 为新的空 List。
  4. 令 hasIndices 为 ToBoolean(? Get(regexp, "hasIndices")).
  5. 如果 hasIndices 是 true,则将码元 0x0064 (LATIN SMALL LETTER D) 追加到 codeUnits。
  6. 令 global 为 ToBoolean(? Get(regexp, "global")).
  7. 如果 global 是 true,则将码元 0x0067 (LATIN SMALL LETTER G) 追加到 codeUnits。
  8. 令 ignoreCase 为 ToBoolean(? Get(regexp, "ignoreCase")).
  9. 如果 ignoreCase 是 true,则将码元 0x0069 (LATIN SMALL LETTER I) 追加到 codeUnits。
  10. 令 multiline 为 ToBoolean(? Get(regexp, "multiline")).
  11. 如果 multiline 是 true,则将码元 0x006D (LATIN SMALL LETTER M) 追加到 codeUnits。
  12. 令 dotAll 为 ToBoolean(? Get(regexp, "dotAll")).
  13. 如果 dotAll 是 true,则将码元 0x0073 (LATIN SMALL LETTER S) 追加到 codeUnits。
  14. 令 unicode 为 ToBoolean(? Get(regexp, "unicode")).
  15. 如果 unicode 是 true,则将码元 0x0075 (LATIN SMALL LETTER U) 追加到 codeUnits。
  16. 令 unicodeSets 为 ToBoolean(? Get(regexp, "unicodeSets")).
  17. 如果 unicodeSets 是 true,则将码元 0x0076 (LATIN SMALL LETTER V) 追加到 codeUnits。
  18. 令 sticky 为 ToBoolean(? Get(regexp, "sticky")).
  19. 如果 sticky 是 true,则将码元 0x0079 (LATIN SMALL LETTER Y) 追加到 codeUnits。
  20. 返回其码元为 List codeUnits 中各元素的 String 值。如果 codeUnits 没有元素,则返回空 String。

22.2.6.4.1 RegExpHasFlag ( regexp, codeUnit )

抽象操作 RegExpHasFlag,接收参数 regexp (ECMAScript 语言值) 和 codeUnit (码元);返回值:(正常完成 (值:(Boolean 或 undefined)) 或 抛出完成)。 调用时执行以下步骤:

  1. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  2. 如果 regexp 没有 [[OriginalFlags]] 内部槽,则
    1. 如果 SameValue(regexp, %RegExp.prototype%) 是 true,则返回 undefined。
    2. 抛出 TypeError 异常。
  3. 令 flags 为 regexp.[[OriginalFlags]]。
  4. 如果 flags 包含 codeUnit,则返回 true。
  5. 返回 false。

22.2.6.5 get RegExp.prototype.global

RegExp.prototype.global 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 令 codeUnit 为码元 0x0067 (LATIN SMALL LETTER G)。
  3. 返回 ? RegExpHasFlag(regexp, codeUnit)。

22.2.6.6 get RegExp.prototype.hasIndices

RegExp.prototype.hasIndices 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 令 codeUnit 为码元 0x0064 (LATIN SMALL LETTER D)。
  3. 返回 ? RegExpHasFlag(regexp, codeUnit)。

22.2.6.7 get RegExp.prototype.ignoreCase

RegExp.prototype.ignoreCase 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 令 codeUnit 为码元 0x0069 (LATIN SMALL LETTER I)。
  3. 返回 ? RegExpHasFlag(regexp, codeUnit)。

22.2.6.8 RegExp.prototype [ %Symbol.match% ] ( string )

调用时,此方法执行以下步骤:

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 将 string 设置为 ? ToString(string)。
  4. 令 flags 为 ? ToString(? Get(regexp, "flags")).
  5. 如果 flags 不包含 "g",则返回 ? RegExpExec(regexp, string)。
  6. 如果 flags 包含 "u" 或 flags 包含 "v",则令 fullUnicode 为 true;否则令 fullUnicode 为 false。
  7. 执行 ? Set(regexp, "lastIndex", +0𝔽, true)。
  8. 令 array 为 ! ArrayCreate(0)。
  9. 令 matchCount 为 0。
  10. 重复执行,
    1. 令 result 为 ? RegExpExec(regexp, string)。
    2. 如果 result 是 null,则
      1. 如果 matchCount = 0,则返回 null。
      2. 返回 array。
    3. 令 matchString 为 ? ToString(? Get(result, "0")).
    4. 执行 ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(matchCount)), matchString)。
    5. 如果 matchString 是空 String,则
      1. 令 thisIndex 为 ℝ(? ToLength(? Get(regexp, "lastIndex")))。
      2. 令 nextIndex 为 AdvanceStringIndex(string, thisIndex, fullUnicode)。
      3. 执行 ? Set(regexp, "lastIndex", 𝔽(nextIndex), true)。
    6. 将 matchCount 设置为 matchCount + 1。

此方法的 "name" 属性值是 "[Symbol.match]"。

注

%Symbol.match% 属性由 IsRegExp 抽象操作用于识别具有正则表达式基本行为的对象。缺少 %Symbol.match% 属性,或者存在该属性但其值进行 Boolean 强制转换后不为 true,表示该对象并非旨在用作正则表达式对象。

22.2.6.9 RegExp.prototype [ %Symbol.matchAll% ] ( string )

调用时,此方法执行以下步骤:

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 将 string 设置为 ? ToString(string)。
  4. 令 speciesCtor 为 ? SpeciesConstructor(regexp, %RegExp%)。
  5. 令 flags 为 ? ToString(? Get(regexp, "flags")).
  6. 令 matcher 为 ? Construct(speciesCtor, « regexp, flags »)。
  7. 令 lastIndex 为 ? ToLength(? Get(regexp, "lastIndex")).
  8. 执行 ? Set(matcher, "lastIndex", lastIndex, true)。
  9. 如果 flags 包含 "g",则令 global 为 true。
  10. 否则,令 global 为 false。
  11. 如果 flags 包含 "u" 或 flags 包含 "v",则令 fullUnicode 为 true。
  12. 否则,令 fullUnicode 为 false。
  13. 返回 CreateRegExpStringIterator(matcher, string, global, fullUnicode)。

此方法的 "name" 属性值是 "[Symbol.matchAll]"。

22.2.6.10 get RegExp.prototype.multiline

RegExp.prototype.multiline 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 令 codeUnit 为码元 0x006D (LATIN SMALL LETTER M)。
  3. 返回 ? RegExpHasFlag(regexp, codeUnit)。

22.2.6.11 RegExp.prototype [ %Symbol.replace% ] ( string, replaceValue )

调用时,此方法执行以下步骤:

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 将 string 设置为 ? ToString(string)。
  4. 令 stringLength 为 string 的长度。
  5. 令 functionalReplace 为 IsCallable(replaceValue)。
  6. 如果 functionalReplace 是 false,则
    1. 将 replaceValue 设置为 ? ToString(replaceValue)。
  7. 令 flags 为 ? ToString(? Get(regexp, "flags")).
  8. 如果 flags 包含 "g",则令 global 为 true;否则令 global 为 false。
  9. 如果 global 是 true,则
    1. 执行 ? Set(regexp, "lastIndex", +0𝔽, true)。
  10. 令 results 为新的空 List。
  11. 令 done 为 false。
  12. 当 done 是 false 时,重复执行,
    1. 令 result 为 ? RegExpExec(regexp, string)。
    2. 如果 result 是 null,则
      1. 将 done 设置为 true。
    3. 否则,
      1. 将 result 追加到 results。
      2. 如果 global 是 false,则
        1. 将 done 设置为 true。
      3. 否则,
        1. 令 matchString 为 ? ToString(? Get(result, "0")).
        2. 如果 matchString 是空 String,则
          1. 令 thisIndex 为 ℝ(? ToLength(? Get(regexp, "lastIndex")))。
          2. 如果 flags 包含 "u" 或 flags 包含 "v",则令 fullUnicode 为 true;否则令 fullUnicode 为 false。
          3. 令 nextIndex 为 AdvanceStringIndex(string, thisIndex, fullUnicode)。
          4. 执行 ? Set(regexp, "lastIndex", 𝔽(nextIndex), true)。
  13. 令 accumulatedResult 为空 String。
  14. 令 nextSourcePosition 为 0。
  15. 对 results 的每个元素 result,执行
    1. 令 resultLength 为 ? LengthOfArrayLike(result)。
    2. 令 capturesCount 为 max(resultLength - 1, 0)。
    3. 令 matched 为 ? ToString(? Get(result, "0")).
    4. 令 matchLength 为 matched 的长度。
    5. 令 position 为 ? ToIntegerOrInfinity(? Get(result, "index")).
    6. 将 position 设置为将 position 限制在 0 和 stringLength 之间的结果。
    7. 令 captures 为新的空 List。
    8. 令 captureNumber 为 1。
    9. 当 captureNumber ≤ capturesCount 时,重复执行,
      1. 令 capture 为 ? Get(result, ! ToString(𝔽(captureNumber)))。
      2. 如果 capture 不是 undefined,则
        1. 将 capture 设置为 ? ToString(capture)。
      3. 将 capture 追加到 captures。
      4. 注:当 captureNumber = 1 时,前一步会将第一个元素放入 captures(索引 0)。更一般地,第 captureNumberth 个捕获(由第 captureNumberth 组捕获括号捕获的字符)位于 captures[captureNumber - 1]。
      5. 将 captureNumber 设置为 captureNumber + 1。
    10. 令 namedCaptures 为 ? Get(result, "groups")。
    11. 如果 functionalReplace 是 true,则
      1. 令 replacerArgs 为 « matched »、captures 和 « 𝔽(position), string » 的列表连接。
      2. 如果 namedCaptures 不是 undefined,则
        1. 将 namedCaptures 追加到 replacerArgs。
      3. 令 replacementValue 为 ? Call(replaceValue, undefined, replacerArgs)。
      4. 令 replacementString 为 ? ToString(replacementValue)。
    12. 否则,
      1. 如果 namedCaptures 不是 undefined,则
        1. 将 namedCaptures 设置为 ? ToObject(namedCaptures)。
      2. 令 replacementString 为 ? GetSubstitution(matched, string, position, captures, namedCaptures, replaceValue)。
    13. 如果 position ≥ nextSourcePosition,则
      1. 注:position 通常不应向后移动。如果发生这种情况,则表明存在行为不当的 RegExp 子类,或者使用由访问触发的副作用改变 regexp 的 global 标志或其他特征。在这种情况下,相应的替换会被忽略。
      2. 将 accumulatedResult 设置为 accumulatedResult、string 从 nextSourcePosition 到 position 的子字符串以及 replacementString 的字符串连接。
      3. 将 nextSourcePosition 设置为 position + matchLength。
  16. 如果 nextSourcePosition ≥ stringLength,则返回 accumulatedResult。
  17. 返回 accumulatedResult 和 string 从 nextSourcePosition 开始的子字符串的字符串连接。

此方法的 "name" 属性值是 "[Symbol.replace]"。

22.2.6.12 RegExp.prototype [ %Symbol.search% ] ( string )

调用时,此方法执行以下步骤:

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 将 string 设置为 ? ToString(string)。
  4. 令 previousLastIndex 为 ? Get(regexp, "lastIndex")。
  5. 如果 previousLastIndex 不是 +0𝔽,则
    1. 执行 ? Set(regexp, "lastIndex", +0𝔽, true)。
  6. 令 result 为 ? RegExpExec(regexp, string)。
  7. 令 currentLastIndex 为 ? Get(regexp, "lastIndex")。
  8. 如果 SameValue(currentLastIndex, previousLastIndex) 是 false,则
    1. 执行 ? Set(regexp, "lastIndex", previousLastIndex, true)。
  9. 如果 result 是 null,则返回 -1𝔽。
  10. 返回 ? Get(result, "index")。

此方法的 "name" 属性值是 "[Symbol.search]"。

注

执行搜索时,会忽略此 RegExp 对象的 "lastIndex" 和 "global" 属性。"lastIndex" 属性保持不变。

22.2.6.13 get RegExp.prototype.source

RegExp.prototype.source 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 如果 regexp 没有 [[OriginalSource]] 内部槽,则
    1. 如果 SameValue(regexp, %RegExp.prototype%) 是 true,则返回 "(?:)"。
    2. 抛出 TypeError 异常。
  4. 断言:regexp 具有 [[OriginalFlags]] 内部槽。
  5. 令 source 为 regexp.[[OriginalSource]]。
  6. 令 flags 为 regexp.[[OriginalFlags]]。
  7. 返回 EscapeRegExpPattern(source, flags)。

22.2.6.13.1 EscapeRegExpPattern ( pattern, flags )

抽象操作 EscapeRegExpPattern,接收参数 pattern (String) 和 flags (String);返回值:String。 调用时执行以下步骤:

  1. 如果 flags 包含 "v",则
    1. 令 patternSymbol 为 Pattern[+UnicodeMode, +UnicodeSetsMode]。
  2. 否则如果 flags 包含 "u",则
    1. 令 patternSymbol 为 Pattern[+UnicodeMode, ~UnicodeSetsMode]。
  3. 否则,
    1. 令 patternSymbol 为 Pattern[~UnicodeMode, ~UnicodeSetsMode]。
  4. 令 escapedPattern 为形式为 patternSymbol 的 String,它等价于将 pattern 解释为 UTF-16 编码 Unicode 码点(6.1.4),其中某些码点按下述方式进行转义。escapedPattern 可以与 pattern 相同,也可以不同;不过,将 escapedPattern 作为 patternSymbol 求值所得的 Abstract Closure 必须与构造对象的 [[RegExpMatcher]] 内部槽所给出的 Abstract Closure 行为完全相同。使用相同 pattern 和 flags 值多次调用此抽象操作时,必须产生相同结果。
  5. 模式中出现的码点 / 或任何 LineTerminator 都应在 escapedPattern 中按需要进行转义,以确保 "/"、escapedPattern、"/" 和 flags 的字符串连接可以(在适当的词法上下文中)解析为行为与所构造正则表达式完全相同的 RegularExpressionLiteral。例如,如果 pattern 是 "/",则 escapedPattern 可以是 "\/" 或 "\u002F" 等,但不能是 "/",因为 /// 后跟 flags 会被解析为 SingleLineComment,而不是 RegularExpressionLiteral。如果 pattern 是空 String,则可以令 escapedPattern 为 "(?:)" 来满足本规范。
  6. 返回 escapedPattern。
注

尽管名称相似,RegExp.escape 和 EscapeRegExpPattern 执行的操作并不相似。前者转义字符串以便在模式内部表示,而此函数转义模式以便表示为字符串。

22.2.6.14 RegExp.prototype [ %Symbol.split% ] ( string, limit )

注 1

此方法返回一个 Array,其中存储了将 string 转换为 String 所得结果的子字符串。这些子字符串通过从左到右搜索 this value 正则表达式的匹配来确定;这些出现位置不属于返回数组中的任何 String,而是用于分割 String 值。

this value 可以是空正则表达式,也可以是能够匹配空 String 的正则表达式。在这种情况下,正则表达式不匹配输入 String 开头或末尾的空子字符串,也不匹配上一个分隔符匹配末尾的空子字符串。(例如,如果正则表达式匹配空 String,则 String 会被拆分成单独的码元元素;结果数组的长度等于 String 的长度,并且每个子字符串包含一个码元。)在 String 的给定索引处只考虑第一次匹配,即使回溯可以在该索引处得到非空子字符串匹配。(例如,/a*?/[Symbol.split]("ab") 求值为数组 ["a", "b"],而 /a*/[Symbol.split]("ab") 求值为数组 ["","b"]。)

如果 string 是空 String(或转换为后是空 String),则结果取决于正则表达式是否能够匹配空 String。如果可以,则结果数组不包含任何元素。否则,结果数组包含一个元素,即空 String。

如果正则表达式包含捕获括号,则每次匹配 separator 时,捕获括号的结果(包括任何 undefined 结果)都会插入输出数组。例如,

/<(\/)?([^<>]+)>/[Symbol.split]("A<B>bold</B>and<CODE>coded</CODE>")

求值为数组

["A", undefined, "B", "bold", "/", "B", "and", undefined, "CODE", "coded", "/", "CODE", ""]

如果 limit 不是 undefined,则输出数组会被截断,使其包含的元素不超过 limit 个。

调用时,此方法执行以下步骤:

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 将 string 设置为 ? ToString(string)。
  4. 令 speciesCtor 为 ? SpeciesConstructor(regexp, %RegExp%)。
  5. 令 flags 为 ? ToString(? Get(regexp, "flags")).
  6. 如果 flags 包含 "u" 或 flags 包含 "v",则令 unicodeMatching 为 true。
  7. 否则,令 unicodeMatching 为 false。
  8. 如果 flags 包含 "y",则令 newFlags 为 flags。
  9. 否则,令 newFlags 为 flags 和 "y" 的字符串连接。
  10. 令 splitter 为 ? Construct(speciesCtor, « regexp, newFlags »)。
  11. 令 array 为 ! ArrayCreate(0)。
  12. 令 lengthA 为 0。
  13. 如果 limit 是 undefined,则令 lim 为 232 - 1;否则令 lim 为 ℝ(? ToUint32(limit))。
  14. 如果 lim = 0,则返回 array。
  15. 如果 string 是空 String,则
    1. 令 matchResult 为 ? RegExpExec(splitter, string)。
    2. 如果 matchResult 不是 null,则返回 array。
    3. 执行 ! CreateDataPropertyOrThrow(array, "0", string)。
    4. 返回 array。
  16. 令 size 为 string 的长度。
  17. 令 lastMatchEnd 为 0。
  18. 令 searchIndex 为 lastMatchEnd。
  19. 当 searchIndex < size 时,重复执行,
    1. 执行 ? Set(splitter, "lastIndex", 𝔽(searchIndex), true)。
    2. 令 matchResult 为 ? RegExpExec(splitter, string)。
    3. 如果 matchResult 是 null,则
      1. 将 searchIndex 设置为 AdvanceStringIndex(string, searchIndex, unicodeMatching)。
    4. 否则,
      1. 令 matchEnd 为 ℝ(? ToLength(? Get(splitter, "lastIndex")))。
      2. 将 matchEnd 设置为 min(matchEnd, size)。
      3. 如果 matchEnd = lastMatchEnd,则
        1. 将 searchIndex 设置为 AdvanceStringIndex(string, searchIndex, unicodeMatching)。
      4. 否则,
        1. 令 substring 为 string 从 lastMatchEnd 到 searchIndex 的子字符串。
        2. 执行 ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)。
        3. 将 lengthA 设置为 lengthA + 1。
        4. 如果 lengthA = lim,则返回 array。
        5. 将 lastMatchEnd 设置为 matchEnd。
        6. 令 numberOfCaptures 为 ? LengthOfArrayLike(matchResult)。
        7. 将 numberOfCaptures 设置为 max(numberOfCaptures - 1, 0)。
        8. 令 captureIndex 为 1。
        9. 当 captureIndex ≤ numberOfCaptures 时,重复执行,
          1. 令 nextCapture 为 ? Get(matchResult, ! ToString(𝔽(captureIndex)))。
          2. 执行 ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), nextCapture)。
          3. 将 captureIndex 设置为 captureIndex + 1。
          4. 将 lengthA 设置为 lengthA + 1。
          5. 如果 lengthA = lim,则返回 array。
        10. 将 searchIndex 设置为 lastMatchEnd。
  20. 令 substring 为 string 从 lastMatchEnd 到 size 的子字符串。
  21. 执行 ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)。
  22. 返回 array。

此方法的 "name" 属性值是 "[Symbol.split]"。

注 2

此方法忽略该 RegExp 对象的 "global" 和 "sticky" 属性值。

22.2.6.15 get RegExp.prototype.sticky

RegExp.prototype.sticky 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 令 codeUnit 为码元 0x0079 (LATIN SMALL LETTER Y)。
  3. 返回 ? RegExpHasFlag(regexp, codeUnit)。

22.2.6.16 RegExp.prototype.test ( string )

调用时,此方法执行以下步骤:

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 将 string 设置为 ? ToString(string)。
  4. 令 match 为 ? RegExpExec(regexp, string)。
  5. 如果 match 是 null,则返回 false。
  6. 返回 true。

22.2.6.17 RegExp.prototype.toString ( )

  1. 令 regexp 为 this value。
  2. 如果 regexp 不是 Object,则抛出 TypeError 异常。
  3. 令 pattern 为 ? ToString(? Get(regexp, "source")).
  4. 令 flags 为 ? ToString(? Get(regexp, "flags")).
  5. 令 result 为 "/"、pattern、"/" 和 flags 的字符串连接。
  6. 返回 result。
注

返回的 String 具有 RegularExpressionLiteral 的形式,其求值会产生另一个与此对象行为相同的 RegExp 对象。

22.2.6.18 get RegExp.prototype.unicode

RegExp.prototype.unicode 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 令 codeUnit 为码元 0x0075 (LATIN SMALL LETTER U)。
  3. 返回 ? RegExpHasFlag(regexp, codeUnit)。

22.2.6.19 get RegExp.prototype.unicodeSets

RegExp.prototype.unicodeSets 是访问器属性,其 set 访问器函数为 undefined。其 get 访问器函数在调用时执行以下步骤:

  1. 令 regexp 为 this value。
  2. 令 codeUnit 为码元 0x0076 (LATIN SMALL LETTER V)。
  3. 返回 ? RegExpHasFlag(regexp, codeUnit)。

22.2.7 RegExp 匹配的抽象操作

22.2.7.1 RegExpExec ( regexp, string )

抽象操作 RegExpExec,接收参数 regexp (Object) 和 string (String);返回值:(正常完成 (值:(Object 或 null)) 或 抛出完成)。 调用时执行以下步骤:

  1. 令 exec 为 ? Get(regexp, "exec")。
  2. 如果 IsCallable(exec) 是 true,则
    1. 令 result 为 ? Call(exec, regexp, « string »)。
    2. 如果 result 不是 Object 且 result 不是 null,则抛出 TypeError 异常。
    3. 返回 result。
  3. 执行 ? RequireInternalSlot(regexp, [[RegExpMatcher]])。
  4. 返回 ? RegExpBuiltinExec(regexp, string)。
注

如果未找到可调用的 "exec" 属性,此算法会回退到尝试使用内置 RegExp 匹配算法。这为针对早期版本编写的代码提供兼容行为;在那些版本中,大多数使用正则表达式的内置算法不会动态查找 "exec" 属性。

22.2.7.2 RegExpBuiltinExec ( regexp, string )

抽象操作 RegExpBuiltinExec,接收参数 regexp (an initialized RegExp instance) 和 string (String);返回值:(正常完成 (值:(Array 特异对象 或 null)) 或 抛出完成)。 调用时执行以下步骤:

  1. 令 length 为 string 的长度。
  2. 令 lastIndex 为 ℝ(? ToLength(! Get(regexp, "lastIndex")))。
  3. 令 flags 为 regexp.[[OriginalFlags]]。
  4. 如果 flags 包含 "g",则令 global 为 true;否则令 global 为 false。
  5. 如果 flags 包含 "y",则令 sticky 为 true;否则令 sticky 为 false。
  6. 如果 flags 包含 "d",则令 hasIndices 为 true;否则令 hasIndices 为 false。
  7. 如果 global 是 false 且 sticky 是 false,则将 lastIndex 设置为 0。
  8. 令 matcher 为 regexp.[[RegExpMatcher]]。
  9. 如果 flags 包含 "u" 或 flags 包含 "v",则令 fullUnicode 为 true;否则令 fullUnicode 为 false。
  10. 令 matchSucceeded 为 false。
  11. 如果 fullUnicode 是 true,则令 input 为 StringToCodePoints(string);否则令 input 为一个 List,其元素是 string 的元素码元。
  12. 注:input 的每个元素都被视为一个字符。
  13. 当 matchSucceeded 是 false 时,重复执行,
    1. 如果 lastIndex > length,则
      1. 如果 global 是 true 或 sticky 是 true,则
        1. 执行 ? Set(regexp, "lastIndex", +0𝔽, true)。
      2. 返回 null。
    2. 令 inputIndex 为 input 中与 string 的元素 lastIndex 所得到字符对应的索引。
    3. 令 result 为 matcher(input, inputIndex)。
    4. 如果 result 是 failure,则
      1. 如果 sticky 是 true,则
        1. 执行 ? Set(regexp, "lastIndex", +0𝔽, true)。
        2. 返回 null。
      2. 将 lastIndex 设置为 AdvanceStringIndex(string, lastIndex, fullUnicode)。
    5. 否则,
      1. 断言:result 是 MatchState。
      2. 将 matchSucceeded 设置为 true。
  14. 令 endIndex 为 result.[[EndIndex]]。
  15. 如果 fullUnicode 是 true,则将 endIndex 设置为 GetStringIndex(string, endIndex)。
  16. 如果 global 是 true 或 sticky 是 true,则
    1. 执行 ? Set(regexp, "lastIndex", 𝔽(endIndex), true)。
  17. 令 capturingGroupsCount 为 result.[[Captures]] 中的元素数量。
  18. 断言:capturingGroupsCount = regexp.[[RegExpRecord]].[[CapturingGroupsCount]]。
  19. 断言:capturingGroupsCount < 232 - 1。
  20. 令 array 为 ! ArrayCreate(capturingGroupsCount + 1)。
  21. 断言:array 的 "length" 属性的数学值为 capturingGroupsCount + 1。
  22. 执行 ! CreateDataPropertyOrThrow(array, "index", 𝔽(lastIndex))。
  23. 执行 ! CreateDataPropertyOrThrow(array, "input", string)。
  24. 令 match 为 Match Record { [[StartIndex]]: lastIndex, [[EndIndex]]: endIndex }。
  25. 令 indices 为新的空 List。
  26. 令 groupNames 为新的空 List。
  27. 将 match 追加到 indices。
  28. 令 matchedSubstring 为 GetMatchString(string, match)。
  29. 执行 ! CreateDataPropertyOrThrow(array, "0", matchedSubstring)。
  30. 如果 regexp 包含任何 GroupName,则
    1. 令 groups 为 OrdinaryObjectCreate(null)。
    2. 令 hasGroups 为 true。
  31. 否则,
    1. 令 groups 为 undefined。
    2. 令 hasGroups 为 false。
  32. 执行 ! CreateDataPropertyOrThrow(array, "groups", groups)。
  33. 令 matchedGroupNames 为新的空 List。
  34. 按升序,对于满足 1 ≤ i ≤ capturingGroupsCount 的每个整数 i,执行
    1. 令 capture 为 result.[[Captures]] 的第 ith 个元素。
    2. 如果 capture 是 undefined,则
      1. 令 capturedValue 为 undefined。
      2. 将 undefined 追加到 indices。
    3. 否则,
      1. 令 captureStart 为 capture.[[StartIndex]]。
      2. 令 captureEnd 为 capture.[[EndIndex]]。
      3. 如果 fullUnicode 是 true,则
        1. 将 captureStart 设置为 GetStringIndex(string, captureStart)。
        2. 将 captureEnd 设置为 GetStringIndex(string, captureEnd)。
      4. 令 captureRecord 为 Match Record { [[StartIndex]]: captureStart, [[EndIndex]]: captureEnd }。
      5. 令 capturedValue 为 GetMatchString(string, captureRecord)。
      6. 将 captureRecord 追加到 indices。
    4. 执行 ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), capturedValue)。
    5. 如果 regexp 的第 ith 个捕获使用 GroupName 定义,则
      1. 令 groupName 为 CapturingGroupName of that GroupName。
      2. 如果 matchedGroupNames 包含 groupName,则
        1. 断言:capturedValue 是 undefined。
        2. 将 undefined 追加到 groupNames。
      3. 否则,
        1. 如果 capturedValue 不是 undefined,则将 groupName 追加到 matchedGroupNames。
        2. 注:如果存在多个名为 groupName 的组,则此时 groups 可能已经具有 groupName 属性。不过,由于 groups 是一个其属性均为可写数据属性的普通对象,因此对 CreateDataPropertyOrThrow 的调用仍保证成功。
        3. 执行 ! CreateDataPropertyOrThrow(groups, groupName, capturedValue)。
        4. 将 groupName 追加到 groupNames。
    6. 否则,
      1. 将 undefined 追加到 groupNames。
  35. 如果 hasIndices 是 true,则
    1. 令 indicesArray 为 MakeMatchIndicesIndexPairArray(string, indices, groupNames, hasGroups)。
    2. 执行 ! CreateDataPropertyOrThrow(array, "indices", indicesArray)。
  36. 返回 array。

22.2.7.3 AdvanceStringIndex ( string, index, unicode )

抽象操作 AdvanceStringIndex,接收参数 string (String)、index (非负整数) 和 unicode (Boolean);返回值:非负整数。 调用时执行以下步骤:

  1. 断言:index ≤ 253 - 1。
  2. 如果 unicode 是 false,则返回 index + 1。
  3. 令 length 为 string 的长度。
  4. 如果 index + 1 ≥ length,则返回 index + 1。
  5. 令 codePoint 为 CodePointAt(string, index)。
  6. 返回 index + codePoint.[[CodeUnitCount]]。

22.2.7.4 GetStringIndex ( string, codePointIndex )

抽象操作 GetStringIndex,接收参数 string (String) 和 codePointIndex (非负整数);返回值:非负整数。 它按照 6.1.4 中的说明,将 string 解释为 UTF-16 编码码点序列,并在存在相应索引时返回与码点索引 codePointIndex 对应的码元索引。否则,它返回 string 的长度。 调用时执行以下步骤:

  1. 如果 string 是空 String,则返回 0。
  2. 令 length 为 string 的长度。
  3. 令 codeUnitCount 为 0。
  4. 令 codePointCount 为 0。
  5. 当 codeUnitCount < length 时,重复执行,
    1. 如果 codePointCount = codePointIndex,则返回 codeUnitCount。
    2. 令 codePoint 为 CodePointAt(string, codeUnitCount)。
    3. 将 codeUnitCount 设置为 codeUnitCount + codePoint.[[CodeUnitCount]]。
    4. 将 codePointCount 设置为 codePointCount + 1。
  6. 返回 length。

22.2.7.5 Match Record

Match Record 是用于封装正则表达式匹配或捕获的起始和结束索引的 Record。

Match Record 具有 表 68 中列出的字段。

表 68: Match Record 字段
字段名称 值 含义
[[StartIndex]] a non-negative integer 从字符串开头到匹配开始位置(包含)的码元数量。
[[EndIndex]] an integer ≥ [[StartIndex]] 从字符串开头到匹配结束位置(不包含)的码元数量。

22.2.7.6 GetMatchString ( string, match )

抽象操作 GetMatchString,接收参数 string (String) 和 match (Match 记录);返回值:String。 调用时执行以下步骤:

  1. 断言:match.[[StartIndex]] ≤ match.[[EndIndex]] ≤ string 的长度。
  2. 返回 string 从 match.[[StartIndex]] 到 match.[[EndIndex]] 的子字符串。

22.2.7.7 GetMatchIndexPair ( string, match )

抽象操作 GetMatchIndexPair,接收参数 string (String) 和 match (Match 记录);返回值:Array。 调用时执行以下步骤:

  1. 断言:match.[[StartIndex]] ≤ match.[[EndIndex]] ≤ string 的长度。
  2. 返回 CreateArrayFromList(« 𝔽(match.[[StartIndex]]), 𝔽(match.[[EndIndex]]) »)。

22.2.7.8 MakeMatchIndicesIndexPairArray ( string, indices, groupNames, hasGroups )

抽象操作 MakeMatchIndicesIndexPairArray,接收参数 string (String)、indices (列表 (元素:(Match 记录 或 undefined)))、groupNames (列表 (元素:(String 或 undefined))) 和 hasGroups (Boolean);返回值:Array。 调用时执行以下步骤:

  1. 令 n 为 indices 中的元素数量。
  2. 断言:n < 232 - 1。
  3. 断言:groupNames 有 n - 1 个元素。
  4. 注:groupNames List 包含从 indices[1] 开始与 indices List 对齐的元素。
  5. 令 array 为 ! ArrayCreate(n)。
  6. 如果 hasGroups 是 true,则
    1. 令 groups 为 OrdinaryObjectCreate(null)。
  7. 否则,
    1. 令 groups 为 undefined。
  8. 执行 ! CreateDataPropertyOrThrow(array, "groups", groups)。
  9. 按升序,对于满足 0 ≤ i < n 的每个整数 i,执行
    1. 令 matchIndices 为 indices[i]。
    2. 如果 matchIndices 不是 undefined,则
      1. 令 matchIndexPair 为 GetMatchIndexPair(string, matchIndices)。
    3. 否则,
      1. 令 matchIndexPair 为 undefined。
    4. 执行 ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), matchIndexPair)。
    5. 如果 i > 0,则
      1. 令 name 为 groupNames[i - 1]。
      2. 如果 name 不是 undefined,则
        1. 断言:groups 不是 undefined。
        2. 注:如果存在多个名为 name 的组,则此时 groups 可能已经具有 name 属性。不过,由于 groups 是一个其属性均为可写数据属性的普通对象,因此对 CreateDataPropertyOrThrow 的调用仍保证成功。
        3. 执行 ! CreateDataPropertyOrThrow(groups, name, matchIndexPair)。
  10. 返回 array。

22.2.8 RegExp 实例的属性

RegExp 实例是从 RegExp 原型对象继承属性的普通对象。RegExp 实例具有内部槽 [[OriginalSource]]、[[OriginalFlags]]、[[RegExpRecord]] 和 [[RegExpMatcher]]。[[RegExpMatcher]] 内部槽的值是 RegExp 对象的 Pattern 的 Abstract Closure 表示。

注

在 ECMAScript 2015 之前,RegExp 实例被规定具有自有数据属性 "source"、"global"、"ignoreCase" 和 "multiline"。这些属性现在被规定为 RegExp.prototype 的访问器属性。

RegExp 实例还具有以下属性:

22.2.8.1 lastIndex

"lastIndex" 属性的值指定开始下一次匹配的 String 索引。使用时会将其强制转换为整数 Number(参见 22.2.7.2)。此属性应具有特性 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }。

22.2.9 RegExp String 迭代器对象

RegExp String Iterator 是表示对某个特定 String 实例对象进行某次特定迭代,同时与某个特定 RegExp 实例对象进行匹配的对象。RegExp String Iterator 对象没有具名构造函数。相反,RegExp String Iterator 对象通过调用 RegExp 实例对象的某些方法创建。

22.2.9.1 CreateRegExpStringIterator ( regexp, string, global, fullUnicode )

抽象操作 CreateRegExpStringIterator,接收参数 regexp (Object)、string (String)、global (Boolean) 和 fullUnicode (Boolean);返回值:Object。 调用时执行以下步骤:

  1. 令 iterator 为 OrdinaryObjectCreate(%RegExpStringIteratorPrototype%, « [[IteratingRegExp]], [[IteratedString]], [[Global]], [[Unicode]], [[Done]] »)。
  2. 将 iterator.[[IteratingRegExp]] 设置为 regexp。
  3. 将 iterator.[[IteratedString]] 设置为 string。
  4. 将 iterator.[[Global]] 设置为 global。
  5. 将 iterator.[[Unicode]] 设置为 fullUnicode。
  6. 将 iterator.[[Done]] 设置为 false。
  7. 返回 iterator。

22.2.9.2 %RegExpStringIteratorPrototype% 对象

%RegExpStringIteratorPrototype% 对象:

22.2.9.2.1 %RegExpStringIteratorPrototype%.next ( )

  1. 令 iteratorObj 为 this value。
  2. 如果 iteratorObj 不是 Object,则抛出 TypeError 异常。
  3. 如果 iteratorObj 不具有 RegExp String Iterator Object Instance 的所有内部槽(参见 22.2.9.3),则抛出 TypeError 异常。
  4. 如果 iteratorObj.[[Done]] 是 true,则
    1. 返回 CreateIteratorResultObject(undefined, true)。
  5. 令 regexp 为 iteratorObj.[[IteratingRegExp]]。
  6. 令 string 为 iteratorObj.[[IteratedString]]。
  7. 令 global 为 iteratorObj.[[Global]]。
  8. 令 fullUnicode 为 iteratorObj.[[Unicode]]。
  9. 令 match 为 ? RegExpExec(regexp, string)。
  10. 如果 match 是 null,则
    1. 将 iteratorObj.[[Done]] 设置为 true。
    2. 返回 CreateIteratorResultObject(undefined, true)。
  11. 如果 global 是 false,则
    1. 将 iteratorObj.[[Done]] 设置为 true。
    2. 返回 CreateIteratorResultObject(match, false)。
  12. 令 matchString 为 ? ToString(? Get(match, "0")).
  13. 如果 matchString 是空 String,则
    1. 令 thisIndex 为 ℝ(? ToLength(? Get(regexp, "lastIndex")))。
    2. 令 nextIndex 为 AdvanceStringIndex(string, thisIndex, fullUnicode)。
    3. 执行 ? Set(regexp, "lastIndex", 𝔽(nextIndex), true)。
  14. 返回 CreateIteratorResultObject(match, false)。

22.2.9.2.2 %RegExpStringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 属性的初始值是 String 值 "RegExp String Iterator"。

此属性具有特性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }。

22.2.9.3 RegExp String Iterator 实例的属性

RegExp String Iterator 实例是从 %RegExpStringIteratorPrototype% 内在对象继承属性的普通对象。RegExp String Iterator 实例最初创建时具有 表 69 中列出的内部槽。

表 69: RegExp String Iterator 实例的内部槽
内部槽 类型 描述
[[IteratingRegExp]] an Object 用于迭代的正则表达式。IsRegExp([[IteratingRegExp]]) 的初始值是 true。
[[IteratedString]] a String 正在被迭代的 String 值。
[[Global]] a Boolean 表示 [[IteratingRegExp]] 是否为全局正则表达式。
[[Unicode]] a Boolean 表示 [[IteratingRegExp]] 是否处于 Unicode 模式。
[[Done]] a Boolean 表示迭代是否完成。