22 텍스트 처리

22.1 String 객체

22.1.1 String 생성자

String 생성자는:

  • %String%이다.
  • 전역 객체"String" 속성의 초기값이다.
  • 생성자로 호출될 때 새로운 String 객체를 생성하고 초기화한다.
  • 생성자가 아니라 함수로 호출될 때 타입 변환을 수행한다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 String 동작을 상속하려는 서브클래스 생성자는 [[StringData]] 내부 슬롯을 가진 서브클래스 인스턴스를 생성하고 초기화하기 위해 String 생성자에 대한 super 호출을 포함해야 한다.

22.1.1.1 String ( value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. value가 존재하지 않으면,
    1. str을 빈 String이라고 하자.
  2. 그렇지 않으면,
    1. NewTarget이 undefined이고 value가 Symbol이면, SymbolDescriptiveString(value)을 반환한다.
    2. str을 ? ToString(value)라고 하자.
  3. NewTarget이 undefined이면 str을 반환한다.
  4. StringCreate(str, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%"))를 반환한다.

22.1.2 String 생성자의 속성

String 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

22.1.2.1 String.fromCharCode ( ...codeUnits )

이 함수는 나머지 매개변수 codeUnits를 형성하는 임의 개수의 인자와 함께 호출될 수 있다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. result를 빈 String이라고 하자.
  2. codeUnits의 각 요소 next에 대해, 다음을 수행한다.
    1. nextCU를 수치 값이 (? ToUint16(next))인 코드 단위라고 하자.
    2. resultresultnextCU의 문자열 연결로 설정한다.
  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. resultresultUTF16EncodeCodePoint((nextCP))의 문자열 연결로 설정한다.
  3. Assert: 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. substitutionCountsubstitutions의 요소 개수라고 하자.
  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. nextLiteralVal을 ? Get(literals, ! ToString(𝔽(nextIndex)))라고 하자.
    2. nextLiteral을 ? ToString(nextLiteralVal)라고 하자.
    3. resultresultnextLiteral의 문자열 연결로 설정한다.
    4. nextIndex + 1 = literalCount이면, result를 반환한다.
    5. nextIndex < substitutionCount이면,
      1. nextSubValsubstitutions[nextIndex]라고 하자.
      2. nextSub를 ? ToString(nextSubVal)라고 하자.
      3. resultresultnextSub의 문자열 연결로 설정한다.
    6. nextIndexnextIndex + 1로 설정한다.
Note

이 함수는 Tagged Template(13.3.11)의 태그 함수로 사용되도록 의도되어 있다. 그렇게 호출될 때, 첫 번째 인자는 올바른 형식의 템플릿 객체이고 나머지 매개변수는 치환 값을 포함한다.

22.1.3 String 프로토타입 객체의 속성

String 프로토타입 객체는:

  • %String.prototype%이다.
  • String 특수 객체이며 그러한 객체에 대해 지정된 내부 메서드를 가진다.
  • 값이 빈 String인 [[StringData]] 내부 슬롯을 가진다.
  • 초기값이 +0𝔽이고 속성 특성이 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }인 "length" 속성을 가진다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.

명시적으로 달리 언급되지 않는 한, 아래에 정의된 String 프로토타입 객체의 메서드는 제네릭이 아니며, 그 메서드에 전달되는 this 값은 String 값이거나 String 값으로 초기화된 [[StringData]] 내부 슬롯을 가진 객체여야 한다.

22.1.3.1 String.prototype.at ( index )

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. lenstr의 길이라고 하자.
  5. relativeIndex를 ? ToIntegerOrInfinity(index)라고 하자.
  6. relativeIndex ≥ 0이면,
    1. krelativeIndex라고 하자.
  7. 그렇지 않으면,
    1. klen + relativeIndex라고 하자.
  8. k < 0이거나 klen이면, undefined를 반환한다.
  9. strk부터 k + 1까지의 부분 문자열을 반환한다.

22.1.3.2 String.prototype.charAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 결과인 String 값 안의 인덱스 pos에 있는 코드 단위를 포함하는 단일 요소 String을 반환한다. 그 인덱스에 요소가 없으면 결과는 빈 String이다. 결과는 String 객체가 아니라 String 값이다.

pos정수 Number이면, x.charAt(pos)의 결과는 x.substring(pos, pos + 1)의 결과와 동등하다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. position을 ? ToIntegerOrInfinity(pos)라고 하자.
  5. sizestr의 길이라고 하자.
  6. position < 0이거나 positionsize이면, 빈 String을 반환한다.
  7. strposition부터 position + 1까지의 부분 문자열을 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.3 String.prototype.charCodeAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 결과인 String 안의 인덱스 pos에 있는 코드 단위의 수치 값인 Number(216보다 작은 음이 아닌 정수 Number)를 반환한다. 그 인덱스에 요소가 없으면 결과는 NaN이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. position을 ? ToIntegerOrInfinity(pos)라고 하자.
  5. sizestr의 길이라고 하자.
  6. position < 0이거나 positionsize이면, NaN을 반환한다.
  7. String str 안의 인덱스 position에 있는 코드 단위의 수치 값에 대한 Number 값을 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.4 String.prototype.codePointAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 결과인 String 안의 인덱스 pos에 있는 문자열 요소에서 시작하는 UTF-16으로 인코딩된 코드 포인트(6.1.4)의 수치 값인 0x10FFFF𝔽 이하의 음이 아닌 정수 Number를 반환한다. 그 인덱스에 요소가 없으면 결과는 undefined이다. 유효한 UTF-16 서로게이트 쌍이 pos에서 시작하지 않으면, 결과는 pos에 있는 코드 단위이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. position을 ? ToIntegerOrInfinity(pos)라고 하자.
  5. sizestr의 길이라고 하자.
  6. position < 0이거나 positionsize이면, undefined를 반환한다.
  7. cpCodePointAt(str, position)이라고 하자.
  8. 𝔽(cp.[[CodePoint]])를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

Note 1

이 메서드가 호출되면, this 값(문자열로 변환됨)의 코드 단위들 뒤에 각각의 인자를 String으로 변환한 코드 단위들이 이어진 String 값을 반환한다. 결과는 String 객체가 아니라 String 값이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. resultstr이라고 하자.
  5. args의 각 요소 next에 대해, 다음을 수행한다.
    1. nextString을 ? ToString(next)라고 하자.
    2. resultresultnextString의 문자열 연결로 설정한다.
  6. result를 반환한다.

이 메서드의 "length" 속성은 1𝔽이다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.6 String.prototype.constructor

String.prototype.constructor의 초기값은 %String%이다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. isRegExp를 ? IsRegExp(searchString)라고 하자.
  5. isRegExptrue이면, TypeError 예외를 던진다.
  6. searchStr을 ? ToString(searchString)라고 하자.
  7. lenstr의 길이라고 하자.
  8. endPositionundefined이면 poslen이라고 하자; 그렇지 않으면 pos를 ? ToIntegerOrInfinity(endPosition)라고 하자.
  9. endpos를 0과 len 사이로 클램프한 결과라고 하자.
  10. searchLengthsearchStr의 길이라고 하자.
  11. searchLength = 0이면, true를 반환한다.
  12. startend - searchLength라고 하자.
  13. start < 0이면, false를 반환한다.
  14. substringstrstart부터 end까지의 부분 문자열이라고 하자.
  15. substringsearchStr이면, true를 반환한다.
  16. false를 반환한다.
Note 1

첫 번째 인자가 RegExp이면 예외를 던지도록 지정된 것은 그러한 인자 값을 허용하는 확장을 미래 판에서 정의할 수 있게 하기 위한 것이다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. isRegExp를 ? IsRegExp(searchString)라고 하자.
  5. isRegExptrue이면, TypeError 예외를 던진다.
  6. searchStr을 ? ToString(searchString)라고 하자.
  7. pos를 ? ToIntegerOrInfinity(position)라고 하자.
  8. Assert: positionundefined이면, pos는 0이다.
  9. lenstr의 길이라고 하자.
  10. startpos를 0과 len 사이로 클램프한 결과라고 하자.
  11. indexStringIndexOf(str, searchStr, start)라고 하자.
  12. indexnot-found이면, false를 반환한다.
  13. true를 반환한다.
Note 1

searchString이 이 객체를 String으로 변환한 결과의 부분 문자열로서, position 이상인 하나 이상의 인덱스에 나타나면, 이 함수는 true를 반환한다; 그렇지 않으면 false를 반환한다. positionundefined이면, 전체 String을 검색하기 위해 0이 가정된다.

Note 2

첫 번째 인자가 RegExp이면 예외를 던지도록 지정된 것은 그러한 인자 값을 허용하는 확장을 미래 판에서 정의할 수 있게 하기 위한 것이다.

Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

Note 1

searchString이 이 객체를 String으로 변환한 결과의 부분 문자열로서, position 이상인 하나 이상의 인덱스에 나타나면, 그러한 가장 작은 인덱스가 반환된다; 그렇지 않으면 -1𝔽이 반환된다. positionundefined이면, 전체 String을 검색하기 위해 +0𝔽이 가정된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. searchStr을 ? ToString(searchString)라고 하자.
  5. pos를 ? ToIntegerOrInfinity(position)라고 하자.
  6. Assert: positionundefined이면, pos는 0이다.
  7. lenstr의 길이라고 하자.
  8. startpos를 0과 len 사이로 클램프한 결과라고 하자.
  9. resultStringIndexOf(str, searchStr, start)라고 하자.
  10. resultnot-found이면, -1𝔽을 반환한다.
  11. 𝔽(result)를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.10 String.prototype.isWellFormed ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. IsStringWellFormedUnicode(str)를 반환한다.

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

Note 1

searchString이 이 객체를 String으로 변환한 결과의 부분 문자열로서, position 이하인 하나 이상의 인덱스에 나타나면, 그러한 가장 큰 인덱스가 반환된다; 그렇지 않으면 -1𝔽이 반환된다. positionundefined이면, 전체 String을 검색하기 위해 String 값의 길이가 가정된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. searchStr을 ? ToString(searchString)라고 하자.
  5. numPos를 ? ToNumber(position)라고 하자.
  6. Assert: positionundefined이면, numPosNaN이다.
  7. numPosNaN이면 pos를 +∞라고 하자; 그렇지 않으면 pos를 ! ToIntegerOrInfinity(numPos)라고 하자.
  8. lenstr의 길이라고 하자.
  9. searchLensearchStr의 길이라고 하자.
  10. len < searchLen이면, -1𝔽을 반환한다.
  11. startpos를 0과 len - searchLen 사이로 클램프한 결과라고 하자.
  12. resultStringLastIndexOf(str, searchStr, start)라고 하자.
  13. resultnot-found이면, -1𝔽을 반환한다.
  14. 𝔽(result)를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 this 값(String str로 변환됨)과 that(String thatValue로 변환됨)의 구현 정의 로캘 민감 String 비교 결과를 나타내는 NaN이 아닌 Number를 반환한다. 결과는 호스트 환경의 현재 로캘 관례에 따른 String 값의 정렬 순서에 대응하도록 의도되어 있으며, strthatValue보다 앞에 정렬되면 음수, strthatValue보다 뒤에 정렬되면 양수, 그 밖의 모든 경우에는 0(strthatValue 사이에 상대적 순서가 없음을 나타냄)이 된다.

비교를 수행하기 전에, 이 메서드는 String들을 준비하기 위해 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. thatValue를 ? ToString(that)라고 하자.

이 메서드의 선택적 두 번째 및 세 번째 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치에 다른 어떤 해석도 부여해서는 안 된다.

실제 반환 값은 추가 정보를 인코딩할 수 있도록 구현 정의이지만, 두 인자의 메서드로 간주될 때 이 메서드는 모든 String의 집합에 대한 전순서를 정의하는 일관된 비교자여야 한다. 이 메서드는 또한 Unicode Standard에 따른 정준 동등성을 인식하고 존중해야 하며, 구별 가능한 String들이 정준적으로 동등할 때 +0𝔽을 반환하는 것도 포함한다.

Note 1

후자는 두 인자의 함수를 요구하므로, 이 메서드 자체는 Array.prototype.sort에 대한 인자로 직접 적합하지 않다.

Note 2

이 메서드는 ECMAScript 환경이 호스트 환경으로부터 이용할 수 있는 어떤 언어 및/또는 로캘 민감 비교 기능에 의존할 수 있으며, 호스트 환경의 현재 로캘 관례에 따라 비교하도록 의도되어 있다. 그러나 비교 기능과 관계없이, 이 메서드는 Unicode Standard에 따른 정준 동등성을 인식하고 존중해야 한다. 예를 들어, 다음 비교들은 모두 +0𝔽을 반환해야 한다:

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

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

// ṩ LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE vs.
// ṩ 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 vs.
// ḍ̇ LATIN SMALL LETTER D WITH DOT BELOW + COMBINING DOT ABOVE
"\u1E0B\u0323".localeCompare("\u1E0D\u0307")

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

정준 동등성의 정의와 논의는 Unicode Standard의 2장과 3장 및 Unicode Standard Annex #15, Unicode Normalization FormsUnicode Technical Note #5, Canonical Equivalence in Applications를 보라. 또한 Unicode Technical Standard #10, Unicode Collation Algorithm도 보라.

이 메서드는 Unicode Standard 3장 3.7절에 정의된 Unicode 호환 동등물 또는 호환 분해를 존중하지 않는 것이 권장된다.

Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.13 String.prototype.match ( regexpOrPattern )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면,
    1. matcher를 ? GetMethod(regexpOrPattern, %Symbol.match%)라고 하자.
    2. matcherundefined가 아니면,
      1. Call(matcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. str을 ? ToString(thisValue)라고 하자.
  5. regexp를 ? RegExpCreate(regexpOrPattern, undefined)라고 하자.
  6. Invoke(regexp, %Symbol.match%, « str »)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.14 String.prototype.matchAll ( regexpOrPattern )

이 메서드는 this 값을 나타내는 String을 regexpOrPattern에 대해 정규 표현식 매칭하고, 매치 결과를 산출하는 반복자를 반환한다. 각 매치 결과는 String의 매치된 부분을 첫 번째 요소로 포함하고, 이어서 캡처 그룹에 의해 매치된 부분들을 포함하는 Array이다. 정규 표현식이 전혀 매치되지 않으면, 반환된 반복자는 어떤 매치 결과도 산출하지 않는다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면,
    1. isRegExp를 ? IsRegExp(regexpOrPattern)라고 하자.
    2. isRegExptrue이면,
      1. flags를 ? Get(regexpOrPattern, "flags")라고 하자.
      2. RequireObjectCoercible(flags)를 수행한다.
      3. ToString(flags)가 "g"를 포함하지 않으면, TypeError 예외를 던진다.
    3. matcher를 ? GetMethod(regexpOrPattern, %Symbol.matchAll%)라고 하자.
    4. matcherundefined가 아니면,
      1. Call(matcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. str을 ? ToString(thisValue)라고 하자.
  5. regexp를 ? RegExpCreate(regexpOrPattern, "g")라고 하자.
  6. Invoke(regexp, %Symbol.matchAll%, « str »)를 반환한다.
Note 1
이 메서드는 의도적으로 제네릭이다. 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.
Note 2
String.prototype.split과 유사하게, String.prototype.matchAll은 일반적으로 입력을 변경하지 않고 동작하도록 설계되어 있다.

22.1.3.15 String.prototype.normalize ( [ form ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. formundefined이면, f"NFC"라고 하자.
  5. 그렇지 않으면, f를 ? ToString(form)이라고 하자.
  6. f"NFC", "NFD", "NFKC", 또는 "NFKD" 중 하나가 아니면, RangeError 예외를 던진다.
  7. ns최신 Unicode Standard, Normalization Forms에 지정된 대로 f가 이름 붙인 정규화 형식으로 str을 정규화한 결과인 String 값이라고 하자.
  8. ns를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, end)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, start)를 반환한다.

22.1.3.17.1 StringPaddingBuiltinsImpl ( thisValue, maxLength, fillString, placement )

The abstract operation StringPaddingBuiltinsImpl takes arguments thisValue (an ECMAScript language value), maxLength (an ECMAScript language value), fillString (an ECMAScript language value), and placement (start or end) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. str을 ? ToString(thisValue)라고 하자.
  2. intMaxLength(? ToLength(maxLength))라고 하자.
  3. stringLengthstr의 길이라고 하자.
  4. intMaxLengthstringLength이면, str을 반환한다.
  5. fillStringundefined이면, fillString을 코드 단위 0x0020 (SPACE)만으로 구성된 String 값으로 설정한다.
  6. 그렇지 않으면, fillString을 ? ToString(fillString)으로 설정한다.
  7. StringPad(str, intMaxLength, fillString, placement)를 반환한다.

22.1.3.17.2 StringPad ( str, maxLength, fillString, placement )

The abstract operation StringPad takes arguments str (a String), maxLength (a non-negative integer), fillString (a String), and placement (start or end) and returns a String. It performs the following steps when called:

  1. stringLengthstr의 길이라고 하자.
  2. maxLengthstringLength이면, str을 반환한다.
  3. fillString이 빈 String이면, str을 반환한다.
  4. fillLenmaxLength - stringLength라고 하자.
  5. truncatedStringFillerfillString의 반복 연결로 구성되고 길이 fillLen으로 잘린 String 값이라고 하자.
  6. placementstart이면, truncatedStringFillerstr의 문자열 연결을 반환한다.
  7. strtruncatedStringFiller의 문자열 연결을 반환한다.
Note 1

인자 maxLengthstr의 길이보다 작을 수 없도록 클램프된다.

Note 2

인자 fillString의 기본값은 " " (코드 단위 0x0020 SPACE로 구성된 String 값)이다.

22.1.3.17.3 ToZeroPaddedDecimalString ( n, minLength )

The abstract operation ToZeroPaddedDecimalString takes arguments n (a non-negative integer) and minLength (a non-negative integer) and returns a String. It performs the following steps when called:

  1. strn의 String 표현, 즉 십진수로 형식화된 표현이라고 하자.
  2. StringPad(str, minLength, "0", start)를 반환한다.

22.1.3.18 String.prototype.repeat ( count )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. n을 ? ToIntegerOrInfinity(count)라고 하자.
  5. n < 0이거나 n = +∞이면, RangeError 예외를 던진다.
  6. n = 0이면, 빈 String을 반환한다.
  7. strn개 사본을 함께 이어 붙여 만든 String 값을 반환한다.
Note 1

이 메서드는 this 값(String으로 변환됨)의 코드 단위들이 count번 반복된 String 값을 생성한다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.19 String.prototype.replace ( searchValue, replaceValue )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. searchValue가 Object이면,
    1. replacer를 ? GetMethod(searchValue, %Symbol.replace%)라고 하자.
    2. replacerundefined가 아니면,
      1. Call(replacer, searchValue, « thisValue, replaceValue »)를 반환한다.
  4. string을 ? ToString(thisValue)라고 하자.
  5. searchString을 ? ToString(searchValue)라고 하자.
  6. functionalReplaceIsCallable(replaceValue)라고 하자.
  7. functionalReplacefalse이면,
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  8. searchLengthsearchString의 길이라고 하자.
  9. positionStringIndexOf(string, searchString, 0)이라고 하자.
  10. positionnot-found이면, string을 반환한다.
  11. precedingstring의 0부터 position까지의 부분 문자열이라고 하자.
  12. followingstringposition + searchLength부터의 부분 문자열이라고 하자.
  13. functionalReplacetrue이면,
    1. replacement를 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(position), string »))라고 하자.
  14. 그렇지 않으면,
    1. Assert: replaceValue는 String이다.
    2. captures를 새로운 빈 List라고 하자.
    3. replacement를 ! GetSubstitution(searchString, string, position, captures, undefined, replaceValue)라고 하자.
  15. preceding, replacement, 및 following의 문자열 연결을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

The abstract operation GetSubstitution takes arguments matched (a String), str (a String), position (a non-negative integer), captures (a List of either Strings or undefined), namedCaptures (an Object or undefined), and replacementTemplate (a String) and returns either a normal completion containing a String or a throw completion. 이 추상 연산의 목적상, 십진 숫자는 0x0030 (DIGIT ZERO)부터 0x0039 (DIGIT NINE)까지의 포함 구간에 있는 코드 단위이다. It performs the following steps when called:

  1. stringLengthstr의 길이라고 하자.
  2. Assert: positionstringLength.
  3. result를 빈 String이라고 하자.
  4. templateRemainderreplacementTemplate이라고 하자.
  5. templateRemainder가 빈 String이 아닌 동안 반복한다.
    1. NOTE: 다음 단계들은 ref(templateRemainder의 접두사)를 분리하고, refReplacement(그 대체)를 결정한 다음, 그 대체를 result에 덧붙인다.
    2. templateRemainder"$$"로 시작하면,
      1. ref"$$"라고 하자.
      2. refReplacement"$"라고 하자.
    3. 그렇지 않고 templateRemainder"$`"로 시작하면,
      1. ref"$`"라고 하자.
      2. refReplacementstr의 0부터 position까지의 부분 문자열이라고 하자.
    4. 그렇지 않고 templateRemainder"$&"로 시작하면,
      1. ref"$&"라고 하자.
      2. refReplacementmatched라고 하자.
    5. 그렇지 않고 templateRemainder"$'" (0x0024 (DOLLAR SIGN) 뒤에 0x0027 (APOSTROPHE))로 시작하면,
      1. ref"$'"라고 하자.
      2. matchLengthmatched의 길이라고 하자.
      3. tailPosposition + matchLength라고 하자.
      4. refReplacementstrmin(tailPos, stringLength)부터의 부분 문자열이라고 하자.
      5. NOTE: tailPos는 이 추상 연산"exec" 속성이 내장 %RegExp.prototype.exec%가 아닌 객체에 대한 %RegExp.prototype%의 내장 %Symbol.replace% 메서드 호출에 의해 호출된 경우에만 stringLength를 초과할 수 있다.
    6. 그렇지 않고 templateRemainder"$" 뒤에 1개 이상의 십진 숫자가 이어지는 것으로 시작하면,
      1. templateRemainder"$" 뒤에 2개 이상의 십진 숫자가 이어지는 것으로 시작하면 digitCount를 2라고 하자; 그렇지 않으면 digitCount를 1이라고 하자.
      2. digitstemplateRemainder의 1부터 1 + digitCount까지의 부분 문자열이라고 하자.
      3. index(StringToNumber(digits))라고 하자.
      4. Assert: 0 ≤ index ≤ 99.
      5. captureLencaptures의 요소 개수라고 하자.
      6. index > captureLen이고 digitCount = 2이면,
        1. NOTE: 두 자리 대체 패턴이 캡처링 그룹 수를 초과하는 인덱스를 지정하면, 한 자리 대체 패턴 뒤에 리터럴 숫자가 이어지는 것으로 취급된다.
        2. digitCount를 1로 설정한다.
        3. digitsdigits의 0부터 1까지의 부분 문자열로 설정한다.
        4. index(StringToNumber(digits))로 설정한다.
      7. reftemplateRemainder의 0부터 1 + digitCount까지의 부분 문자열이라고 하자.
      8. 1 ≤ indexcaptureLen이면,
        1. capturecaptures[index - 1]이라고 하자.
        2. captureundefined이면,
          1. refReplacement를 빈 String이라고 하자.
        3. 그렇지 않으면,
          1. refReplacementcapture라고 하자.
      9. 그렇지 않으면,
        1. refReplacementref라고 하자.
    7. 그렇지 않고 templateRemainder"$<"로 시작하면,
      1. gtPosStringIndexOf(templateRemainder, ">", 0)이라고 하자.
      2. gtPosnot-found이거나 namedCapturesundefined이면,
        1. ref"$<"라고 하자.
        2. refReplacementref라고 하자.
      3. 그렇지 않으면,
        1. reftemplateRemainder의 0부터 gtPos + 1까지의 부분 문자열이라고 하자.
        2. groupNametemplateRemainder의 2부터 gtPos까지의 부분 문자열이라고 하자.
        3. Assert: namedCaptures는 Object이다.
        4. capture를 ? Get(namedCaptures, groupName)라고 하자.
        5. captureundefined이면,
          1. refReplacement를 빈 String이라고 하자.
        6. 그렇지 않으면,
          1. refReplacement를 ? ToString(capture)라고 하자.
    8. 그렇지 않으면,
      1. reftemplateRemainder의 0부터 1까지의 부분 문자열이라고 하자.
      2. refReplacementref라고 하자.
    9. refLengthref의 길이라고 하자.
    10. templateRemaindertemplateRemainderrefLength부터의 부분 문자열로 설정한다.
    11. resultresultrefReplacement의 문자열 연결로 설정한다.
  6. result를 반환한다.

22.1.3.20 String.prototype.replaceAll ( searchValue, replaceValue )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. searchValue가 Object이면,
    1. isRegExp를 ? IsRegExp(searchValue)라고 하자.
    2. isRegExptrue이면,
      1. flags를 ? Get(searchValue, "flags")라고 하자.
      2. RequireObjectCoercible(flags)를 수행한다.
      3. ToString(flags)가 "g"를 포함하지 않으면, TypeError 예외를 던진다.
    3. replacer를 ? GetMethod(searchValue, %Symbol.replace%)라고 하자.
    4. replacerundefined가 아니면,
      1. Call(replacer, searchValue, « thisValue, replaceValue »)를 반환한다.
  4. string을 ? ToString(thisValue)라고 하자.
  5. searchString을 ? ToString(searchValue)라고 하자.
  6. functionalReplaceIsCallable(replaceValue)라고 하자.
  7. functionalReplacefalse이면,
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  8. searchLengthsearchString의 길이라고 하자.
  9. advanceBymax(1, searchLength)라고 하자.
  10. matchPositions를 새로운 빈 List라고 하자.
  11. positionStringIndexOf(string, searchString, 0)이라고 하자.
  12. positionnot-found가 아닌 동안 반복한다.
    1. positionmatchPositions에 추가한다.
    2. positionStringIndexOf(string, searchString, position + advanceBy)로 설정한다.
  13. endOfLastMatch를 0이라고 하자.
  14. result를 빈 String이라고 하자.
  15. matchPositions의 각 요소 matchPosition에 대해, 다음을 수행한다.
    1. preservedstringendOfLastMatch부터 matchPosition까지의 부분 문자열이라고 하자.
    2. functionalReplacetrue이면,
      1. replacement를 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(matchPosition), string »))라고 하자.
    3. 그렇지 않으면,
      1. Assert: replaceValue는 String이다.
      2. captures를 새로운 빈 List라고 하자.
      3. replacement를 ! GetSubstitution(searchString, string, matchPosition, captures, undefined, replaceValue)라고 하자.
    4. resultresult, preserved, 및 replacement의 문자열 연결로 설정한다.
    5. endOfLastMatchmatchPosition + searchLength로 설정한다.
  16. endOfLastMatch < string의 길이면,
    1. resultresultstringendOfLastMatch부터의 부분 문자열의 문자열 연결로 설정한다.
  17. result를 반환한다.

22.1.3.21 String.prototype.search ( regexpOrPattern )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면,
    1. searcher를 ? GetMethod(regexpOrPattern, %Symbol.search%)라고 하자.
    2. searcherundefined가 아니면,
      1. Call(searcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. string을 ? ToString(thisValue)라고 하자.
  5. regexp를 ? RegExpCreate(regexpOrPattern, undefined)라고 하자.
  6. Invoke(regexp, %Symbol.search%, « string »)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.22 String.prototype.slice ( start, end )

이 메서드는 이 객체를 String으로 변환한 결과의 부분 문자열을 반환한다. 이 부분 문자열은 인덱스 start에서 시작하여 인덱스 end까지 진행하되 end는 포함하지 않는다(또는 endundefined이면 String의 끝까지). start가 음수이면, String의 길이인 sourceLength에 대해 sourceLength + start로 취급된다. end가 음수이면, String의 길이인 sourceLength에 대해 sourceLength + end로 취급된다. 결과는 String 객체가 아니라 String 값이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. lenstr의 길이라고 하자.
  5. intStart를 ? ToIntegerOrInfinity(start)라고 하자.
  6. intStart = -∞이면, from을 0이라고 하자.
  7. 그렇지 않고 intStart < 0이면, frommax(len + intStart, 0)이라고 하자.
  8. 그렇지 않으면, frommin(intStart, len)이라고 하자.
  9. endundefined이면 intEndlen이라고 하자; 그렇지 않으면 intEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  10. intEnd = -∞이면, to를 0이라고 하자.
  11. 그렇지 않고 intEnd < 0이면, tomax(len + intEnd, 0)이라고 하자.
  12. 그렇지 않으면, tomin(intEnd, len)이라고 하자.
  13. fromto이면, 빈 String을 반환한다.
  14. strfrom부터 to까지의 부분 문자열을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.23 String.prototype.split ( separator, limit )

이 메서드는 이 객체를 String으로 변환한 결과의 부분 문자열들이 저장된 Array를 반환한다. 부분 문자열들은 separator의 출현을 왼쪽에서 오른쪽으로 검색하여 결정된다; 이러한 출현들은 반환된 배열 안의 어떤 String의 일부도 아니지만, String 값을 나누는 역할을 한다. separator의 값은 임의 길이의 String일 수도 있고, RegExp처럼 %Symbol.split% 메서드를 가진 객체일 수도 있다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. separator가 Object이면,
    1. splitter를 ? GetMethod(separator, %Symbol.split%)라고 하자.
    2. splitterundefined가 아니면,
      1. Call(splitter, separator, « thisValue, limit »)를 반환한다.
  4. str을 ? ToString(thisValue)라고 하자.
  5. limitundefined이면 lim을 232 - 1이라고 하자; 그렇지 않으면 lim(? ToUint32(limit))라고 하자.
  6. separatorStr을 ? ToString(separator)라고 하자.
  7. lim = 0이면,
    1. CreateArrayFromList(« »)를 반환한다.
  8. separatorundefined이면,
    1. CreateArrayFromListstr »)를 반환한다.
  9. separatorLengthseparatorStr의 길이라고 하자.
  10. separatorLength = 0이면,
    1. strLenstr의 길이라고 하자.
    2. outLenlim을 0과 strLen 사이로 클램프한 결과라고 하자.
    3. headstr의 0부터 outLen까지의 부분 문자열이라고 하자.
    4. codeUnitshead의 요소인 코드 단위들의 시퀀스로 구성된 List라고 하자.
    5. CreateArrayFromList(codeUnits)를 반환한다.
  11. str이 빈 String이면, CreateArrayFromListstr »)를 반환한다.
  12. substrings를 새로운 빈 List라고 하자.
  13. searchStart를 0이라고 하자.
  14. matchIndexStringIndexOf(str, separatorStr, 0)이라고 하자.
  15. matchIndexnot-found가 아닌 동안 반복한다.
    1. substringstrsearchStart부터 matchIndex까지의 부분 문자열이라고 하자.
    2. substringsubstrings에 추가한다.
    3. substrings의 요소 개수가 lim이면, CreateArrayFromList(substrings)를 반환한다.
    4. searchStartmatchIndex + separatorLength로 설정한다.
    5. matchIndexStringIndexOf(str, separatorStr, searchStart)로 설정한다.
  16. substringstrsearchStart부터의 부분 문자열이라고 하자.
  17. substringsubstrings에 추가한다.
  18. CreateArrayFromList(substrings)를 반환한다.
Note 1

separator의 값은 빈 String일 수 있다. 이 경우 separator는 입력 String의 시작이나 끝에 있는 빈 부분 문자열과 매치되지 않으며, 이전 구분자 매치의 끝에 있는 빈 부분 문자열과도 매치되지 않는다. separator가 빈 String이면, String은 개별 코드 단위 요소들로 분할된다; 결과 배열의 길이는 String의 길이와 같으며, 각 부분 문자열은 하나의 코드 단위를 포함한다.

this 값이 빈 String이거나 빈 String으로 변환되는 경우, 결과는 separator가 빈 String과 매치될 수 있는지에 따라 달라진다. 매치될 수 있으면 결과 배열은 요소를 포함하지 않는다. 그렇지 않으면 결과 배열은 빈 String인 하나의 요소를 포함한다.

separatorundefined이면, 결과 배열은 this 값(String으로 변환됨)인 하나의 String만 포함한다. limitundefined가 아니면, 출력 배열은 limit개 이하의 요소만 포함하도록 잘린다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. isRegExp를 ? IsRegExp(searchString)라고 하자.
  5. isRegExptrue이면, TypeError 예외를 던진다.
  6. searchStr을 ? ToString(searchString)라고 하자.
  7. lenstr의 길이라고 하자.
  8. positionundefined이면 pos를 0이라고 하자; 그렇지 않으면 pos를 ? ToIntegerOrInfinity(position)라고 하자.
  9. startpos를 0과 len 사이로 클램프한 결과라고 하자.
  10. searchLengthsearchStr의 길이라고 하자.
  11. searchLength = 0이면, true를 반환한다.
  12. endstart + searchLength라고 하자.
  13. end > len이면, false를 반환한다.
  14. substringstrstart부터 end까지의 부분 문자열이라고 하자.
  15. substringsearchStr이면, true를 반환한다.
  16. false를 반환한다.
Note 1

첫 번째 인자가 RegExp이면 예외를 던지도록 지정된 것은 그러한 인자 값을 허용하는 확장을 미래 판에서 정의할 수 있게 하기 위한 것이다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.25 String.prototype.substring ( start, end )

이 메서드는 이 객체를 String으로 변환한 결과의 부분 문자열을 반환한다. 이 부분 문자열은 인덱스 start에서 시작하여 String의 인덱스 end까지 진행하되 end는 포함하지 않는다(또는 endundefined이면 String의 끝까지). 결과는 String 객체가 아니라 String 값이다.

어느 인자든 NaN이거나 음수이면 0으로 대체된다; 어느 인자든 String의 길이보다 엄격히 크면 String의 길이로 대체된다.

startend보다 엄격히 크면, 둘은 서로 바뀐다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. lenstr의 길이라고 하자.
  5. intStart를 ? ToIntegerOrInfinity(start)라고 하자.
  6. endundefined이면 intEndlen이라고 하자; 그렇지 않으면 intEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  7. finalStartintStart를 0과 len 사이로 클램프한 결과라고 하자.
  8. finalEndintEnd를 0과 len 사이로 클램프한 결과라고 하자.
  9. frommin(finalStart, finalEnd)라고 하자.
  10. tomax(finalStart, finalEnd)라고 하자.
  11. strfrom부터 to까지의 부분 문자열을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호스트 환경의 현재 로캘 관례에 대응하는 로캘 민감 결과를 산출하도록 의도된다는 점을 제외하면 toLowerCase와 정확히 동일하게 동작한다. 해당 언어의 규칙이 일반 Unicode 대소문자 매핑과 충돌하는 몇몇 경우(예: 터키어)에만 차이가 있다.

이 메서드의 선택적 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치를 다른 어떤 용도로도 사용해서는 안 된다.

Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호스트 환경의 현재 로캘 관례에 대응하는 로캘 민감 결과를 산출하도록 의도된다는 점을 제외하면 toUpperCase와 정확히 동일하게 동작한다. 해당 언어의 규칙이 일반 Unicode 대소문자 매핑과 충돌하는 몇몇 경우(예: 터키어)에만 차이가 있다.

이 메서드의 선택적 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치를 다른 어떤 용도로도 사용해서는 안 된다.

Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.28 String.prototype.toLowerCase ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. sTextStringToCodePoints(str)라고 하자.
  5. lowerText를 Unicode Default Case Conversion 알고리즘에 따라 toLowercase(sText)라고 하자.
  6. lowercaseStringCodePointsToString(lowerText)라고 하자.
  7. lowercaseString을 반환한다.

결과는 Unicode Character Database의 로캘 비민감 대소문자 매핑에 따라 도출되어야 한다(이는 UnicodeData.txt 파일뿐만 아니라 그와 함께 제공되는 SpecialCasing.txt 파일의 모든 로캘 비민감 매핑도 명시적으로 포함한다).

Note 1

일부 코드 포인트의 대소문자 매핑은 여러 코드 포인트를 생성할 수 있다. 이 경우 결과 String은 원본 String과 같은 길이가 아닐 수 있다. toUpperCasetoLowerCase 모두 문맥 민감 동작을 가지므로, 이 메서드들은 대칭적이지 않다. 다시 말해, s.toUpperCase().toLowerCase()는 반드시 s.toLowerCase()와 같지는 않다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.29 String.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. ThisStringValue(this value)를 반환한다.
Note

String 객체의 경우, 이 메서드는 우연히 valueOf 메서드와 같은 것을 반환한다.

22.1.3.30 String.prototype.toUpperCase ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

String이 Unicode Default Case Conversion의 toUppercase 알고리즘을 사용해 매핑된다는 점을 제외하면, 이 메서드는 String.prototype.toLowerCase와 정확히 같은 방식으로 동작한다.

Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.31 String.prototype.toWellFormed ( )

이 메서드는 서로게이트 쌍의 일부가 아닌 모든 선행 서로게이트와 후행 서로게이트가 U+FFFD (REPLACEMENT CHARACTER)로 대체된 이 객체의 String 표현을 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. strLenstr의 길이라고 하자.
  5. k를 0이라고 하자.
  6. result를 빈 String이라고 하자.
  7. k < strLen인 동안 반복한다.
    1. cpCodePointAt(str, k)라고 하자.
    2. cp.[[IsUnpairedSurrogate]]true이면,
      1. resultresult와 0xFFFD (REPLACEMENT CHARACTER)의 문자열 연결로 설정한다.
    3. 그렇지 않으면,
      1. resultresultUTF16EncodeCodePoint(cp.[[CodePoint]])의 문자열 연결로 설정한다.
    4. kk + cp.[[CodeUnitCount]]로 설정한다.
  8. result를 반환한다.

22.1.3.32 String.prototype.trim ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. TrimString(thisValue, start+end)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.32.1 TrimString ( string, where )

The abstract operation TrimString takes arguments string (an ECMAScript language value) and where (start, end, or start+end) and returns either a normal completion containing a String or a throw completion. 이 연산은 6.1.4에 설명된 대로 string을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다. It performs the following steps when called:

  1. RequireObjectCoercible(string)를 수행한다.
  2. str을 ? ToString(string)라고 하자.
  3. wherestart이면,
    1. trimmedStringstr의 선행 공백 문자가 제거된 복사본인 String 값이라고 하자.
  4. 그렇지 않고 whereend이면,
    1. trimmedStringstr의 후행 공백 문자가 제거된 복사본인 String 값이라고 하자.
  5. 그렇지 않으면,
    1. Assert: wherestart+end이다.
    2. trimmedStringstr의 선행 및 후행 공백 문자가 모두 제거된 복사본인 String 값이라고 하자.
  6. trimmedString을 반환한다.

공백 문자의 정의는 WhiteSpaceLineTerminator의 합집합이다. Unicode 코드 포인트가 Unicode 일반 범주 “Space_Separator” (“Zs”)에 속하는지 결정할 때, 코드 단위 시퀀스는 6.1.4에 지정된 대로 UTF-16으로 인코딩된 코드 포인트 시퀀스로 해석된다.

22.1.3.33 String.prototype.trimEnd ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis 값이라고 하자.
  2. TrimString(str, end)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.34 String.prototype.trimStart ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis 값이라고 하자.
  2. TrimString(str, start)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.35 String.prototype.valueOf ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. ThisStringValue(this value)를 반환한다.

22.1.3.35.1 ThisStringValue ( value )

The abstract operation ThisStringValue takes argument value (an ECMAScript language value) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. value가 String이면, value를 반환한다.
  2. value가 Object이고 value[[StringData]] 내부 슬롯을 가지면,
    1. strvalue.[[StringData]]라고 하자.
    2. Assert: str은 String이다.
    3. str을 반환한다.
  3. TypeError 예외를 던진다.

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

이 메서드는 String 값의 코드 포인트들을 반복하고 각 코드 포인트를 String 값으로 반환하는 반복자 객체를 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis 값이라고 하자.
  2. RequireObjectCoercible(str)를 수행한다.
  3. str을 ? ToString(str)로 설정한다.
  4. closure를 매개변수가 없고 str을 캡처하며 호출될 때 다음 단계를 수행하는 새로운 Abstract Closure라고 하자:
    1. lenstr의 길이라고 하자.
    2. position을 0이라고 하자.
    3. position < len인 동안 반복한다.
      1. cpCodePointAt(str, position)라고 하자.
      2. nextIndexposition + cp.[[CodeUnitCount]]라고 하자.
      3. resultStringstrposition부터 nextIndex까지의 부분 문자열이라고 하자.
      4. positionnextIndex로 설정한다.
      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 Iterator 객체

String Iterator는 특정 String 인스턴스 객체에 대한 특정 반복을 나타내는 객체이다. String Iterator 객체에는 이름 있는 생성자가 없다. 대신, String Iterator 객체는 String 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

22.1.5.1 %StringIteratorPrototype% 객체

%StringIteratorPrototype% 객체는:

  • 모든 String Iterator 객체가 상속하는 속성들을 가진다.
  • 보통 객체이다.
  • 값이 %Iterator.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

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 객체는 정규 표현식과 관련 플래그를 포함한다.

Note

정규 표현식의 형식과 기능은 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 HexLeadSurrogate의 선택이 모호한 각 \u HexTrailSurrogate는, 그렇지 않으면 대응하는 \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] Note 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 & - ! # % , : ; < = > @ ` ~ Note 2

이 절의 여러 생성식에는 B.1.2 절에서 대체 정의가 주어진다.

22.2.1.1 정적 의미론: 조기 오류

Note

이 절은 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 ( node )

The abstract operation CountLeftCapturingParensWithin takes argument node (a Parse Node) and returns a non-negative integer. 이 연산은 node 안의 왼쪽 캡처 괄호의 수를 반환한다. 왼쪽 캡처 괄호 Atom :: ( GroupSpecifieropt Disjunction ) 생성식의 ( 터미널과 일치한 임의의 ( 패턴 문자이다.

Note

이 절은 B.1.2.2에서 수정된다.

It performs the following steps when called:

  1. Assert: nodeRegExp Pattern 문법 안의 생성식의 인스턴스이다.
  2. node 안에 포함된 Atom :: ( GroupSpecifieropt Disjunction ) Parse Node의 수를 반환한다.

22.2.1.3 Static Semantics: CountLeftCapturingParensBefore ( node )

The abstract operation CountLeftCapturingParensBefore takes argument node (a Parse Node) and returns a non-negative integer. 이 연산은 둘러싸는 패턴 안에서 node의 왼쪽에 나타나는 왼쪽 캡처 괄호의 수를 반환한다.

Note

이 절은 B.1.2.2에서 수정된다.

It performs the following steps when called:

  1. Assert: nodeRegExp Pattern 문법 안의 생성식의 인스턴스이다.
  2. patternnode를 포함하는 Pattern이라고 하자.
  3. pattern 안에 포함된 Atom :: ( GroupSpecifieropt Disjunction ) Parse Node 중 node보다 앞에 나타나거나 node를 포함하는 것의 수를 반환한다.

22.2.1.4 Static Semantics: MightBothParticipate ( x, y )

The abstract operation MightBothParticipate takes arguments x (a Parse Node) and y (a Parse Node) and returns a Boolean. It performs the following steps when called:

  1. Assert: xy는 같은 둘러싸는 Pattern을 가진다.
  2. 둘러싸는 Pattern Disjunction :: Alternative | Disjunction Parse Node를 포함하고, xAlternative 안에 포함되며 y가 파생된 Disjunction 안에 포함되거나, x가 파생된 Disjunction 안에 포함되며 yAlternative 안에 포함되면, false를 반환한다.
  3. true를 반환한다.

22.2.1.5 Static Semantics: CapturingGroupNumber

The syntax-directed operation CapturingGroupNumber takes no arguments and returns a positive integer.

Note

이 절은 B.1.2.1에서 수정된다.

It is defined piecewise over the following productions:

DecimalEscape :: NonZeroDigit
  1. NonZeroDigit의 MV를 반환한다.
DecimalEscape :: NonZeroDigit DecimalDigits
  1. nDecimalDigits 안의 코드 포인트 수라고 하자.
  2. (NonZeroDigit의 MV × 10nDecimalDigits의 MV를 더한 값)을 반환한다.

NonZeroDigit의 MV”와 “DecimalDigits의 MV”의 정의는 12.9.3에 있다.

22.2.1.6 Static Semantics: IsCharacterClass

The syntax-directed operation IsCharacterClass takes no arguments and returns a Boolean.

Note

이 절은 B.1.2.3에서 수정된다.

It is defined piecewise over the following productions:

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

The syntax-directed operation CharacterValue takes no arguments and returns a non-negative integer.

Note 1

이 절은 B.1.2.4에서 수정된다.

It is defined piecewise over the following productions:

ClassAtom :: -
  1. U+002D (HYPHEN-MINUS)의 수치 값을 반환한다.
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. chSourceCharacter와 일치한 코드 포인트라고 하자.
  2. ch의 수치 값을 반환한다.
ClassEscape :: b
  1. U+0008 (BACKSPACE)의 수치 값을 반환한다.
ClassEscape :: -
  1. U+002D (HYPHEN-MINUS)의 수치 값을 반환한다.
CharacterEscape :: ControlEscape
  1. Table 62에 따른 수치 값을 반환한다.
Table 62: 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. chAsciiLetter와 일치한 코드 포인트라고 하자.
  2. ich의 수치 값이라고 하자.
  3. i를 32로 나눈 나머지를 반환한다.
CharacterEscape :: 0 [lookahead ∉ DecimalDigit]
  1. U+0000 (NULL)의 수치 값을 반환한다.
Note 2

\0은 <NUL> 문자를 나타내며 뒤에 십진 숫자가 올 수 없다.

CharacterEscape :: HexEscapeSequence
  1. HexEscapeSequence의 MV를 반환한다.
RegExpUnicodeEscapeSequence :: u HexLeadSurrogate \u HexTrailSurrogate
  1. leadHexLeadSurrogateCharacterValue라고 하자.
  2. trailHexTrailSurrogateCharacterValue라고 하자.
  3. cpUTF16SurrogatePairToCodePoint(lead, trail)라고 하자.
  4. cp의 수치 값을 반환한다.
RegExpUnicodeEscapeSequence :: u Hex4Digits
  1. Hex4Digits의 MV를 반환한다.
RegExpUnicodeEscapeSequence :: u{ CodePoint }
  1. CodePoint의 MV를 반환한다.
HexLeadSurrogate :: Hex4Digits HexTrailSurrogate :: Hex4Digits HexNonSurrogate :: Hex4Digits
  1. Hex4Digits의 MV를 반환한다.
CharacterEscape :: IdentityEscape
  1. chIdentityEscape와 일치한 코드 포인트라고 하자.
  2. ch의 수치 값을 반환한다.
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter
  1. chSourceCharacter와 일치한 코드 포인트라고 하자.
  2. ch의 수치 값을 반환한다.
ClassSetCharacter :: \ ClassSetReservedPunctuator
  1. chClassSetReservedPunctuator와 일치한 코드 포인트라고 하자.
  2. ch의 수치 값을 반환한다.
ClassSetCharacter :: \b
  1. U+0008 (BACKSPACE)의 수치 값을 반환한다.

22.2.1.8 Static Semantics: MayContainStrings

The syntax-directed operation MayContainStrings takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

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일치한 소스 텍스트Table 66의 “Property name” 열에 나열된 문자열의 이진 속성이면 true를 반환한다.
  2. false를 반환한다.
ClassUnion :: ClassSetRange ClassUnionopt
  1. ClassUnion이 존재하면, ClassUnionMayContainStrings를 반환한다.
  2. false를 반환한다.
ClassUnion :: ClassSetOperand ClassUnionopt
  1. ClassSetOperandMayContainStringstrue이면, true를 반환한다.
  2. ClassUnion이 존재하면, ClassUnionMayContainStrings를 반환한다.
  3. false를 반환한다.
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. 첫 번째 ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  2. 두 번째 ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  3. true를 반환한다.
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. ClassIntersectionMayContainStringsfalse이면, false를 반환한다.
  2. ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  3. true를 반환한다.
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. 첫 번째 ClassSetOperandMayContainStrings를 반환한다.
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. ClassSubtractionMayContainStrings를 반환한다.
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. ClassStringMayContainStringstrue이면, true를 반환한다.
  2. ClassStringDisjunctionContentsMayContainStrings를 반환한다.
ClassString :: [empty]
  1. true를 반환한다.
ClassString :: NonEmptyClassString
  1. NonEmptyClassStringMayContainStrings를 반환한다.
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. NonEmptyClassString이 존재하면, true를 반환한다.
  2. false를 반환한다.

22.2.1.9 Static Semantics: GroupSpecifiersThatMatch ( thisGroupName )

The abstract operation GroupSpecifiersThatMatch takes argument thisGroupName (a GroupName Parse Node) and returns a List of GroupSpecifier Parse Nodes. It performs the following steps when called:

  1. namethisGroupNameCapturingGroupName이라고 하자.
  2. patternthisGroupName을 포함하는 Pattern이라고 하자.
  3. result를 새로운 빈 List라고 하자.
  4. pattern이 포함하는 각 GroupSpecifier gs에 대해, 다음을 수행한다.
    1. gsCapturingGroupNamename이면,
      1. gsresult에 추가한다.
  5. result를 반환한다.

22.2.1.10 Static Semantics: CapturingGroupName

The syntax-directed operation CapturingGroupName takes no arguments and returns a String. It is defined piecewise over the following productions:

GroupName :: < RegExpIdentifierName >
  1. idTextUnescapedRegExpIdentifierNameRegExpIdentifierCodePoints라고 하자.
  2. CodePointsToString(idTextUnescaped)를 반환한다.

22.2.1.11 Static Semantics: RegExpIdentifierCodePoints

The syntax-directed operation RegExpIdentifierCodePoints takes no arguments and returns a List of code points. It is defined piecewise over the following productions:

RegExpIdentifierName :: RegExpIdentifierStart
  1. cpRegExpIdentifierStartRegExpIdentifierCodePoint라고 하자.
  2. « cp »를 반환한다.
RegExpIdentifierName :: RegExpIdentifierName RegExpIdentifierPart
  1. cps를 파생된 RegExpIdentifierNameRegExpIdentifierCodePoints라고 하자.
  2. cpRegExpIdentifierPartRegExpIdentifierCodePoint라고 하자.
  3. cps와 « cp »의 리스트 연결을 반환한다.

22.2.1.12 Static Semantics: RegExpIdentifierCodePoint

The syntax-directed operation RegExpIdentifierCodePoint takes no arguments and returns a code point. It is defined piecewise over the following productions:

RegExpIdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar와 일치한 코드 포인트를 반환한다.
RegExpIdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar와 일치한 코드 포인트를 반환한다.
RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence
  1. 수치 값이 RegExpUnicodeEscapeSequenceCharacterValue인 코드 포인트를 반환한다.
RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate
  1. leadUnicodeLeadSurrogate와 일치한 코드 포인트의 수치 값이 수치 값인 코드 단위라고 하자.
  2. trailUnicodeTrailSurrogate와 일치한 코드 포인트의 수치 값이 수치 값인 코드 단위라고 하자.
  3. UTF16SurrogatePairToCodePoint(lead, trail)를 반환한다.

22.2.2 패턴 의미론

정규 표현식 패턴은 아래에 설명된 과정을 사용하여 Abstract Closure로 변환된다. 구현은 결과가 동일한 한, 아래에 나열된 알고리즘보다 더 효율적인 알고리즘을 사용하는 것이 권장된다. Abstract Closure는 RegExp 객체의 [[RegExpMatcher]] 내부 슬롯 값으로 사용된다.

Pattern은 관련 플래그가 uv도 포함하지 않으면 BMP 패턴이다. 그렇지 않으면 Unicode 패턴이다. BMP 패턴은 Basic Multilingual Plane 범위의 Unicode 코드 포인트인 16비트 값의 시퀀스로 구성된 것으로 해석되는 String에 대해 매치한다. Unicode 패턴은 UTF-16을 사용해 인코딩된 Unicode 코드 포인트들로 구성된 것으로 해석되는 String에 대해 매치한다. BMP 패턴의 동작을 설명하는 문맥에서 “character”는 단일 16비트 Unicode BMP 코드 포인트를 의미한다. Unicode 패턴의 동작을 설명하는 문맥에서 “character”는 UTF-16으로 인코딩된 코드 포인트(6.1.4)를 의미한다. 어느 문맥에서든 “character value”는 대응하는 인코딩되지 않은 코드 포인트의 수치 값을 의미한다.

Pattern의 구문과 의미론은 Pattern의 소스 텍스트가 각 SourceCharacter가 Unicode 코드 포인트에 대응하는 SourceCharacter 값의 List인 것처럼 정의된다. BMP 패턴이 비-BMP SourceCharacter를 포함하면 전체 패턴이 UTF-16을 사용해 인코딩되고, 그 인코딩의 개별 코드 단위들이 List의 요소로 사용된다.

Note

예를 들어, 단일 비-BMP 문자 U+1D11E (MUSICAL SYMBOL G CLEF)로 소스 텍스트에 표현된 패턴을 생각해 보자. Unicode 패턴으로 해석되면, 이는 단일 코드 포인트 U+1D11E로 구성된 단일 요소(character) List가 된다. 그러나 BMP 패턴으로 해석되면, 먼저 UTF-16으로 인코딩되어 코드 단위 0xD834와 0xDD1E로 구성된 두 요소 List를 생성한다.

패턴은 비-BMP 문자가 UTF-16으로 인코딩된 ECMAScript String 값으로 RegExp 생성자에 전달된다. 예를 들어, 단일 문자 MUSICAL SYMBOL G CLEF 패턴은 String 값으로 표현될 때 요소가 코드 단위 0xD834와 0xDD1E인 길이 2의 String이다. 따라서 두 패턴 문자로 구성된 BMP 패턴으로 처리하기 위해서는 문자열에 대한 추가 변환이 필요하지 않다. 그러나 Unicode 패턴으로 처리하기 위해서는 UTF16SurrogatePairToCodePoint를 사용하여 유일한 요소가 단일 패턴 문자인 코드 포인트 U+1D11E인 List를 생성해야 한다.

구현은 실제로 UTF-16으로 또는 UTF-16에서 이러한 변환을 수행하지 않을 수 있지만, 이 명세의 의미론은 패턴 매칭 결과가 그러한 변환이 수행된 것과 같을 것을 요구한다.

22.2.2.1 표기법

아래 설명은 다음 내부 데이터 구조를 사용한다:

  • CharSetElement는 다음 두 엔티티 중 하나이다:
    • regexpRecord.[[UnicodeSets]]false이면, CharSetElement는 위의 Pattern Semantics의 의미에서의 character이다.
    • regexpRecord.[[UnicodeSets]]true이면, CharSetElement는 위의 Pattern Semantics의 의미에서의 character들을 요소로 가지는 시퀀스이다. 여기에는 빈 시퀀스, 하나의 character로 된 시퀀스, 둘 이상의 character로 된 시퀀스가 포함된다. 편의를 위해, 이러한 종류의 CharSetElement를 다룰 때 개별 character는 하나의 character로 된 시퀀스와 상호 교환적으로 취급된다.
  • CharSet는 CharSetElement들의 수학적 집합이다.
  • CaptureRange는 캡처에 포함된 문자 범위를 나타내는 Record { [[StartIndex]], [[EndIndex]] }이다. 여기서 [[StartIndex]]input 안에서 그 범위의 시작 인덱스(포함)를 나타내는 정수이고, [[EndIndex]]input 안에서 그 범위의 끝 인덱스(제외)를 나타내는 정수이다. 어떤 CaptureRange에 대해서도, 이 인덱스들은 [[StartIndex]][[EndIndex]]라는 불변식을 만족해야 한다.
  • MatchStateRecord { [[Input]], [[EndIndex]], [[Captures]] }이다. 여기서 [[Input]]은 매치되는 String을 나타내는 character들의 List이고, [[EndIndex]]정수이며, [[Captures]]는 패턴의 각 왼쪽 캡처 괄호마다 하나씩 있는 값의 List이다. MatchState는 정규 표현식 매칭 알고리즘에서 부분 매치 상태를 나타내는 데 사용된다. [[EndIndex]]는 지금까지 패턴이 매치한 마지막 입력 character의 인덱스에 1을 더한 값이고, [[Captures]]는 캡처 괄호의 결과를 보관한다. [[Captures]]nth 요소는 nth 캡처 괄호 집합이 캡처한 character 범위를 나타내는 CaptureRange이거나, nth 캡처 괄호 집합에 아직 도달하지 않았으면 undefined이다. 백트래킹 때문에, 매칭 과정 중 언제든 많은 MatchState가 사용 중일 수 있다.
  • MatcherContinuation은 하나의 MatchState 인자를 받아 MatchState 또는 failure를 반환하는 Abstract Closure이다. MatcherContinuation은 자신의 캡처된 값들로 지정된 패턴의 나머지 부분을, 자신의 MatchState 인자가 제공한 중간 상태에서 시작하여 input에 대해 매치하려고 시도한다. 매치가 성공하면 MatcherContinuation은 자신이 도달한 최종 MatchState를 반환하고, 매치가 실패하면 MatcherContinuationfailure를 반환한다.
  • Matcher는 두 인자—MatchStateMatcherContinuation—를 받아 MatchState 또는 failure를 반환하는 Abstract Closure이다. Matcher는 자신의 캡처된 값들로 지정된 패턴의 중간 부분 패턴을, 자신의 MatchState 인자가 제공한 중간 상태에서 시작하여 MatchState[[Input]]에 대해 매치하려고 시도한다. MatcherContinuation 인자는 패턴의 나머지를 매치하는 closure여야 한다. 패턴의 부분 패턴을 매치하여 새로운 MatchState를 얻은 뒤, Matcher는 그 새로운 MatchState에 대해 MatcherContinuation을 호출하여 패턴의 나머지도 매치될 수 있는지 테스트한다. 가능하면 MatcherMatcherContinuation이 반환한 MatchState를 반환한다; 그렇지 않으면 Matcher는 자신의 선택 지점에서 다른 선택들을 시도할 수 있으며, 성공하거나 모든 가능성이 소진될 때까지 MatcherContinuation을 반복적으로 호출한다.

22.2.2.1.1 RegExp Records

RegExp Record는 컴파일 중, 그리고 가능하면 매칭 중 필요한 RegExp에 관한 정보를 저장하는 데 사용되는 Record 값이다.

다음 필드들을 가진다:

Table 63: RegExp Record 필드
필드 이름 의미
[[IgnoreCase]] Boolean RegExp의 플래그에 "i"가 나타나는지 나타낸다
[[Multiline]] Boolean RegExp의 플래그에 "m"이 나타나는지 나타낸다
[[DotAll]] Boolean RegExp의 플래그에 "s"가 나타나는지 나타낸다
[[Unicode]] Boolean RegExp의 플래그에 "u"가 나타나는지 나타낸다
[[UnicodeSets]] Boolean RegExp의 플래그에 "v"가 나타나는지 나타낸다
[[CapturingGroupsCount]] 음이 아닌 정수 RegExp 패턴 안의 왼쪽 캡처 괄호의 수

22.2.2.2 Runtime Semantics: CompilePattern

The syntax-directed operation CompilePattern takes argument regexpRecord (a RegExp Record) and returns a Abstract Closure that takes a List of characters and a non-negative integer and returns either a MatchState or failure. It is defined piecewise over the following productions:

Pattern :: Disjunction
  1. m을 인자 regexpRecordforwardDisjunctionCompileSubpattern이라고 하자.
  2. regexpRecordm을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (input, index)를 가진 새로운 Abstract Closure를 반환한다:
    1. Assert: input은 character들의 List이다.
    2. Assert: 0 ≤ indexinput 안의 요소 개수.
    3. c를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. cap을 1부터 regexpRecord.[[CapturingGroupsCount]]까지 인덱스되는, regexpRecord.[[CapturingGroupsCount]]개의 undefined 값으로 된 List라고 하자.
    5. xMatchState { [[Input]]: input, [[EndIndex]]: index, [[Captures]]: cap }라고 하자.
    6. m(x, c)를 반환한다.
Note

Pattern은 Abstract Closure 값으로 컴파일된다. 그러면 RegExpBuiltinExec는 이 절차를 character들의 List와 그 List 안의 오프셋에 적용하여, 패턴이 그 List 안의 정확히 그 오프셋에서 시작하여 매치되는지, 그리고 매치된다면 캡처 괄호들의 값이 무엇인지 결정할 수 있다. 22.2.2의 알고리즘들은 패턴 컴파일이 SyntaxError 예외를 던질 수 있도록 설계되어 있다; 반면 패턴이 성공적으로 컴파일된 뒤에는 character들의 List에서 매치를 찾기 위해 결과 Abstract Closure를 적용해도 예외를 던질 수 없다(메모리 부족처럼 어디서든 발생할 수 있는 구현 정의 예외는 제외).

22.2.2.3 Runtime Semantics: CompileSubpattern

The syntax-directed operation CompileSubpattern takes arguments regexpRecord (a RegExp Record) and direction (forward or backward) and returns a Matcher.

Note 1

이 절은 B.1.2.5에서 수정된다.

It is defined piecewise over the following productions:

Disjunction :: Alternative | Disjunction
  1. m1을 인자 regexpRecorddirection으로 AlternativeCompileSubpattern이라고 하자.
  2. m2를 인자 regexpRecorddirection으로 DisjunctionCompileSubpattern이라고 하자.
  3. MatchTwoAlternatives(m1, m2)를 반환한다.
Note 2

| 정규 표현식 연산자는 두 대안을 구분한다. 패턴은 먼저 왼쪽 Alternative(|regular expression|의 후속 부분이 뒤따름)를 매치하려고 시도한다; 실패하면 오른쪽 Disjunction(|regular expression|의 후속 부분이 뒤따름)를 매치하려고 시도한다. 왼쪽 Alternative, 오른쪽 Disjunction, 그리고 후속 부분 모두 선택 지점을 가지면, 왼쪽 Alternative의 다음 선택으로 넘어가기 전에 후속 부분의 모든 선택이 시도된다. 왼쪽 Alternative의 선택이 소진되면, 왼쪽 Alternative 대신 오른쪽 Disjunction이 시도된다. |에 의해 건너뛴 패턴 부분 안의 캡처 괄호는 String 대신 undefined 값을 생성한다. 따라서 예를 들어,

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

"ab"가 아니라 "a"라는 결과를 반환한다. 또한,

/((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을 인자 regexpRecorddirection으로 AlternativeCompileSubpattern이라고 하자.
  2. m2를 인자 regexpRecorddirection으로 TermCompileSubpattern이라고 하자.
  3. MatchSequence(m1, m2, direction)를 반환한다.
Note 3

연속된 Term들은 input의 연속된 부분들을 동시에 매치하려고 시도한다. directionforward이면, 왼쪽 Alternative, 오른쪽 Term, 그리고 정규 표현식의 후속 부분 모두 선택 지점을 가지는 경우, 오른쪽 Term의 다음 선택으로 넘어가기 전에 후속 부분의 모든 선택이 시도되고, 왼쪽 Alternative의 다음 선택으로 넘어가기 전에 오른쪽 Term의 모든 선택이 시도된다. directionbackward이면, AlternativeTerm의 평가 순서가 반대로 된다.

Term :: Assertion
  1. 인자 regexpRecordAssertionCompileAssertion을 반환한다.
Note 4

결과 Matcherdirection과 무관하다.

Term :: Atom
  1. 인자 regexpRecorddirection으로 AtomCompileAtom을 반환한다.
Term :: Atom Quantifier
  1. m을 인자 regexpRecorddirection으로 AtomCompileAtom이라고 하자.
  2. qQuantifierCompileQuantifier라고 하자.
  3. Assert: q.[[Min]]q.[[Max]].
  4. parenIndexCountLeftCapturingParensBefore(Term)라고 하자.
  5. parenCountCountLeftCapturingParensWithin(Atom)이라고 하자.
  6. m, q, parenIndex, 및 parenCount를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, c)를 가진 새로운 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    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 )

The abstract operation RepeatMatcher takes arguments m (a Matcher), min (a non-negative integer), max (a non-negative integer or +∞), greedy (a Boolean), matchState (a MatchState), continue (a MatcherContinuation), parenIndex (a non-negative integer), and parenCount (a non-negative integer) and returns either a MatchState or failure. It performs the following steps when called:

  1. max = 0이면 continue(matchState)를 반환한다.
  2. dm, min, max, greedy, matchState, continue, parenIndex, 및 parenCount를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
    1. Assert: yMatchState이다.
    2. min = 0이고 y.[[EndIndex]] = matchState.[[EndIndex]]이면 failure를 반환한다.
    3. min = 0이면 min2를 0이라고 하자; 그렇지 않으면 min2min - 1이라고 하자.
    4. max = +∞이면 max2를 +∞라고 하자; 그렇지 않으면 max2max - 1이라고 하자.
    5. RepeatMatcher(m, min2, max2, greedy, y, continue, parenIndex, parenCount)를 반환한다.
  3. capmatchState.[[Captures]]의 사본이라고 하자.
  4. parenIndex + 1부터 parenIndex + parenCount까지의 포함 구간에 있는 각 정수 k에 대해, cap[k]를 undefined로 설정한다.
  5. inputmatchState.[[Input]]이라고 하자.
  6. ematchState.[[EndIndex]]라고 하자.
  7. xrMatchState { [[Input]]: input, [[EndIndex]]: e, [[Captures]]: cap }라고 하자.
  8. min ≠ 0이면 m(xr, d)를 반환한다.
  9. greedyfalse이면,
    1. zcontinue(matchState)라고 하자.
    2. zfailure가 아니면 z를 반환한다.
    3. m(xr, d)를 반환한다.
  10. zm(xr, d)라고 하자.
  11. zfailure가 아니면 z를 반환한다.
  12. continue(matchState)를 반환한다.
Note 1

Quantifier가 뒤따르는 AtomQuantifier가 지정한 횟수만큼 반복된다. Quantifier는 비탐욕적일 수 있으며, 이 경우 Atom 패턴은 후속 부분을 여전히 매치하면서 가능한 한 적은 횟수로 반복된다. 또는 탐욕적일 수 있으며, 이 경우 Atom 패턴은 후속 부분을 여전히 매치하면서 가능한 한 많은 횟수로 반복된다. 반복되는 것은 Atom이 매치하는 입력 문자 시퀀스가 아니라 Atom 패턴이므로, Atom의 서로 다른 반복은 서로 다른 입력 부분 문자열과 매치할 수 있다.

Note 2

Atom과 정규 표현식의 후속 부분 모두 선택 지점을 가지면, Atom은 먼저 가능한 한 많은 횟수(또는 비탐욕적인 경우 가능한 한 적은 횟수)로 매치된다. Atom의 마지막 반복의 다음 선택으로 넘어가기 전에 후속 부분의 모든 선택이 시도된다. Atom의 마지막(nth) 반복의 모든 선택은 Atom의 끝에서 두 번째((n - 1)st) 반복의 다음 선택으로 넘어가기 전에 시도된다; 그 시점에서 Atom의 더 많거나 더 적은 반복이 이제 가능하다는 것이 드러날 수 있다; 이들은 (다시, 가능한 한 적게 또는 가능한 한 많이 시작하여) 소진된 뒤 Atom의 (n - 1)st 반복의 다음 선택으로 넘어가고, 이런 식으로 계속된다.

다음과 비교해 보라

/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의 gcd를 계산한다:

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

이는 단항 표기법의 gcd "aaaaa"를 반환한다.

Note 3

RepeatMatcher의 단계 4Atom이 반복될 때마다 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이 포함되기 때문이다.

Note 4

RepeatMatcher의 단계 2.b는 최소 반복 횟수가 충족된 뒤에는, 빈 character 시퀀스와 매치하는 Atom의 추가 확장은 더 이상의 반복으로 고려되지 않는다고 명시한다. 이는 정규 표현식 엔진이 다음과 같은 패턴에서 무한 루프에 빠지는 것을 방지한다:

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

또는 약간 더 복잡한:

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

이는 배열

["b", ""]

을 반환한다.

22.2.2.3.2 EmptyMatcher ( )

The abstract operation EmptyMatcher takes no arguments and returns a Matcher. It performs the following steps when called:

  1. 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. continue(matchState)를 반환한다.

22.2.2.3.3 MatchTwoAlternatives ( m1, m2 )

The abstract operation MatchTwoAlternatives takes arguments m1 (a Matcher) and m2 (a Matcher) and returns a Matcher. It performs the following steps when called:

  1. m1m2를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. rm1(matchState, continue)라고 하자.
    4. rfailure가 아니면 r를 반환한다.
    5. m2(matchState, continue)를 반환한다.

22.2.2.3.4 MatchSequence ( m1, m2, direction )

The abstract operation MatchSequence takes arguments m1 (a Matcher), m2 (a Matcher), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. directionforward이면,
    1. m1m2를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
      1. Assert: matchStateMatchState이다.
      2. Assert: continueMatcherContinuation이다.
      3. dcontinuem2를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
        1. Assert: yMatchState이다.
        2. m2(y, continue)를 반환한다.
      4. m1(matchState, d)를 반환한다.
  2. Assert: directionbackward이다.
  3. m1m2를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. dcontinuem1을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. m1(y, continue)를 반환한다.
    4. m2(matchState, d)를 반환한다.

22.2.2.4 Runtime Semantics: CompileAssertion

The syntax-directed operation CompileAssertion takes argument regexpRecord (a RegExp Record) and returns a Matcher.

Note 1

이 절은 B.1.2.6에서 수정된다.

It is defined piecewise over the following productions:

Assertion :: ^
  1. regexpRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]이라고 하자.
    4. ematchState.[[EndIndex]]라고 하자.
    5. e = 0이거나, regexpRecord.[[Multiline]]true이고 character input[e - 1]이 LineTerminator와 일치하면,
      1. continue(matchState)를 반환한다.
    6. failure를 반환한다.
Note 2

y 플래그가 패턴과 함께 사용되더라도, ^는 항상 input의 시작에서만, 또는 (regexpRecord.[[Multiline]]true이면) 줄의 시작에서만 매치한다.

Assertion :: $
  1. regexpRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]이라고 하자.
    4. ematchState.[[EndIndex]]라고 하자.
    5. inputLengthinput 안의 요소 개수라고 하자.
    6. e = inputLength이거나, regexpRecord.[[Multiline]]true이고 character input[e]가 LineTerminator와 일치하면,
      1. continue(matchState)를 반환한다.
    7. failure를 반환한다.
Assertion :: \b
  1. regexpRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]이라고 하자.
    4. ematchState.[[EndIndex]]라고 하자.
    5. aIsWordChar(regexpRecord, input, e - 1)이라고 하자.
    6. bIsWordChar(regexpRecord, input, e)라고 하자.
    7. atrue이고 bfalse이면, 또는 afalse이고 btrue이면, continue(matchState)를 반환한다.
    8. failure를 반환한다.
Assertion :: \B
  1. regexpRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]이라고 하자.
    4. ematchState.[[EndIndex]]라고 하자.
    5. aIsWordChar(regexpRecord, input, e - 1)이라고 하자.
    6. bIsWordChar(regexpRecord, input, e)라고 하자.
    7. atrue이고 btrue이면, 또는 afalse이고 bfalse이면, continue(matchState)를 반환한다.
    8. failure를 반환한다.
Assertion :: (?= Disjunction )
  1. m을 인자 regexpRecordforwardDisjunctionCompileSubpattern이라고 하자.
  2. m을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. d를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. rm(matchState, d)라고 하자.
    5. rfailure이면 failure를 반환한다.
    6. Assert: rMatchState이다.
    7. capr.[[Captures]]라고 하자.
    8. inputmatchState.[[Input]]이라고 하자.
    9. xematchState.[[EndIndex]]라고 하자.
    10. zMatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: cap }라고 하자.
    11. continue(z)를 반환한다.
Note 3

형식 (?= Disjunction )는 너비가 0인 양의 전방탐색을 지정한다. 성공하려면 Disjunction 안의 패턴이 현재 위치에서 매치되어야 하지만, 후속 부분을 매치하기 전에 현재 위치는 전진하지 않는다. Disjunction이 현재 위치에서 여러 방식으로 매치될 수 있으면, 첫 번째 것만 시도된다. 다른 정규 표현식 연산자와 달리, (?= 형식 안으로의 백트래킹은 없다(이 특이한 동작은 Perl에서 상속되었다). 이는 Disjunction이 캡처 괄호를 포함하고 패턴의 후속 부분이 그 캡처들에 대한 역참조를 포함할 때만 중요하다.

예를 들어,

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

는 첫 번째 b 바로 뒤의 빈 String과 매치하므로 배열을 반환한다:

["", "aaa"]

전방탐색 안으로 백트래킹이 없음을 설명하기 위해, 다음을 생각해 보라:

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

이 표현식은 다음을 반환한다

["aba", "a"]

그리고 다음은 반환하지 않는다:

["aaaba", "a"]
Assertion :: (?! Disjunction )
  1. m을 인자 regexpRecordforwardDisjunctionCompileSubpattern이라고 하자.
  2. m을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. d를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. rm(matchState, d)라고 하자.
    5. rfailure가 아니면 failure를 반환한다.
    6. continue(matchState)를 반환한다.
Note 4

형식 (?! Disjunction )는 너비가 0인 음의 전방탐색을 지정한다. 성공하려면 Disjunction 안의 패턴이 현재 위치에서 매치에 실패해야 한다. 후속 부분을 매치하기 전에 현재 위치는 전진하지 않는다. Disjunction은 캡처 괄호를 포함할 수 있지만, 그에 대한 역참조는 Disjunction 자체 안에서만 의미가 있다. 패턴의 다른 곳에서 이 캡처 괄호들에 대한 역참조는 음의 전방탐색이 패턴 성공을 위해 실패해야 하므로 항상 undefined를 반환한다. 예를 들어,

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

는 어떤 양수 n개의 a, b, 또 다른 n개의 a(첫 번째 \2로 지정됨), 그리고 c가 바로 뒤따르지 않는 a를 찾는다. 두 번째 \2는 음의 전방탐색 밖에 있으므로 undefined와 매치하여 항상 성공한다. 전체 표현식은 배열을 반환한다:

["baaabaac", "ba", undefined, "abaac"]
Assertion :: (?<= Disjunction )
  1. m을 인자 regexpRecordbackwardDisjunctionCompileSubpattern이라고 하자.
  2. m을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. d를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. rm(matchState, d)라고 하자.
    5. rfailure이면 failure를 반환한다.
    6. Assert: rMatchState이다.
    7. capr.[[Captures]]라고 하자.
    8. inputmatchState.[[Input]]이라고 하자.
    9. xematchState.[[EndIndex]]라고 하자.
    10. zMatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: cap }라고 하자.
    11. continue(z)를 반환한다.
Assertion :: (?<! Disjunction )
  1. m을 인자 regexpRecordbackwardDisjunctionCompileSubpattern이라고 하자.
  2. m을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. d를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. rm(matchState, d)라고 하자.
    5. rfailure가 아니면 failure를 반환한다.
    6. continue(matchState)를 반환한다.

22.2.2.4.1 IsWordChar ( regexpRecord, input, e )

The abstract operation IsWordChar takes arguments regexpRecord (a RegExp Record), input (a List of characters), and e (an integer) and returns a Boolean. It performs the following steps when called:

  1. inputLengthinput 안의 요소 개수라고 하자.
  2. e = -1이거나 e = inputLength이면 false를 반환한다.
  3. c를 character input[e]라고 하자.
  4. WordCharacters(regexpRecord)가 c를 포함하면 true를 반환한다.
  5. false를 반환한다.

22.2.2.5 Runtime Semantics: CompileQuantifier

The syntax-directed operation CompileQuantifier takes no arguments and returns a Record with fields [[Min]] (a non-negative integer), [[Max]] (a non-negative integer or +∞), and [[Greedy]] (a Boolean). It is defined piecewise over the following productions:

Quantifier :: QuantifierPrefix
  1. qpQuantifierPrefixCompileQuantifierPrefix라고 하자.
  2. Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: true }를 반환한다.
Quantifier :: QuantifierPrefix ?
  1. qpQuantifierPrefixCompileQuantifierPrefix라고 하자.
  2. Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: false }를 반환한다.

22.2.2.6 Runtime Semantics: CompileQuantifierPrefix

The syntax-directed operation CompileQuantifierPrefix takes no arguments and returns a Record with fields [[Min]] (a non-negative integer) and [[Max]] (a non-negative integer or +∞). It is defined piecewise over the following productions:

QuantifierPrefix :: *
  1. Record { [[Min]]: 0, [[Max]]: +∞ }를 반환한다.
QuantifierPrefix :: +
  1. Record { [[Min]]: 1, [[Max]]: +∞ }를 반환한다.
QuantifierPrefix :: ?
  1. Record { [[Min]]: 0, [[Max]]: 1 }를 반환한다.
QuantifierPrefix :: { DecimalDigits }
  1. iDecimalDigits의 MV라고 하자(12.9.3를 보라).
  2. Record { [[Min]]: i, [[Max]]: i }를 반환한다.
QuantifierPrefix :: { DecimalDigits ,}
  1. iDecimalDigits의 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

The syntax-directed operation CompileAtom takes arguments regexpRecord (a RegExp Record) and direction (forward or backward) and returns a Matcher.

Note 1

이 절은 B.1.2.7에서 수정된다.

It is defined piecewise over the following productions:

Atom :: PatternCharacter
  1. chPatternCharacter와 일치한 character라고 하자.
  2. charSet을 character ch를 포함하는 단일 요소 CharSet이라고 하자.
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
Atom :: .
  1. charSetAllCharacters(regexpRecord)라고 하자.
  2. regexpRecord.[[DotAll]]true가 아니면,
    1. LineTerminator 생성식의 오른쪽과 대응하는 코드 포인트에 해당하는 모든 character를 charSet에서 제거한다.
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
Atom :: CharacterClass
  1. cc를 인자 regexpRecordCharacterClassCompileCharacterClass라고 하자.
  2. cscc.[[CharSet]]이라고 하자.
  3. regexpRecord.[[UnicodeSets]]false이거나 cs의 모든 CharSetElement가 단일 character로 구성되어 있으면(cs가 비어 있는 경우 포함), CharacterSetMatcher(regexpRecord, cs, cc.[[Invert]], direction)를 반환한다.
  4. Assert: cc.[[Invert]]false이다.
  5. lmMatchers의 빈 List라고 하자.
  6. cs 안의 둘 이상의 character를 포함하는 각 CharSetElement s에 대해, 길이의 내림차순으로 반복하며, 다음을 수행한다.
    1. cs2s의 마지막 코드 포인트를 포함하는 단일 요소 CharSet이라고 하자.
    2. m2CharacterSetMatcher(regexpRecord, cs2, false, direction)라고 하자.
    3. s 안의 각 코드 포인트 c1에 대해, 그 끝에서 두 번째 코드 포인트부터 역순으로 반복하며, 다음을 수행한다.
      1. cs1c1을 포함하는 단일 요소 CharSet이라고 하자.
      2. m1CharacterSetMatcher(regexpRecord, cs1, false, direction)라고 하자.
      3. m2MatchSequence(m1, m2, direction)로 설정한다.
    4. m2lm에 추가한다.
  7. singles를 단일 character로 구성된 cs의 모든 CharSetElement를 포함하는 CharSet이라고 하자.
  8. CharacterSetMatcher(regexpRecord, singles, false, direction)를 lm에 추가한다.
  9. cs가 character들의 빈 시퀀스를 포함하면 EmptyMatcher()를 lm에 추가한다.
  10. m2lm의 마지막 Matcher라고 하자.
  11. lm의 각 Matcher m1에 대해, 끝에서 두 번째 요소부터 역순으로 반복하며, 다음을 수행한다.
    1. m2MatchTwoAlternatives(m1, m2)로 설정한다.
  12. m2를 반환한다.
Atom :: ( GroupSpecifieropt Disjunction )
  1. m을 인자 regexpRecorddirection으로 DisjunctionCompileSubpattern이라고 하자.
  2. parenIndexCountLeftCapturingParensBefore(Atom)라고 하자.
  3. direction, m, 및 parenIndex를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, c)를 가진 새로운 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. dx, c, direction, 및 parenIndex를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. capy.[[Captures]]의 사본이라고 하자.
      3. inputx.[[Input]]이라고 하자.
      4. xex.[[EndIndex]]라고 하자.
      5. yey.[[EndIndex]]라고 하자.
      6. directionforward이면,
        1. Assert: xeye.
        2. rCaptureRange { [[StartIndex]]: xe, [[EndIndex]]: ye }라고 하자.
      7. 그렇지 않으면,
        1. Assert: directionbackward이다.
        2. Assert: yexe.
        3. rCaptureRange { [[StartIndex]]: ye, [[EndIndex]]: xe }라고 하자.
      8. cap[parenIndex + 1]을 r로 설정한다.
      9. zMatchState { [[Input]]: input, [[EndIndex]]: ye, [[Captures]]: cap }라고 하자.
      10. c(z)를 반환한다.
    4. m(x, d)를 반환한다.
Note 2

형식 ( Disjunction )의 괄호는 Disjunction 패턴의 구성요소를 함께 그룹화하고 매치 결과를 저장하는 두 역할을 모두 한다. 결과는 역참조(\ 뒤에 0이 아닌 십진수가 옴)에서 사용되거나, replace String에서 참조되거나, 정규 표현식 매칭 Abstract Closure에서 배열의 일부로 반환될 수 있다. 괄호의 캡처 동작을 억제하려면 대신 형식 (?: Disjunction )를 사용한다.

Atom :: (? RegularExpressionModifiers : Disjunction )
  1. addModifiersRegularExpressionModifiers일치한 소스 텍스트라고 하자.
  2. removeModifiers를 빈 String이라고 하자.
  3. modifiedRerUpdateModifiers(regexpRecord, CodePointsToString(addModifiers), removeModifiers)라고 하자.
  4. 인자 modifiedRerdirection으로 DisjunctionCompileSubpattern을 반환한다.
Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction )
  1. addModifiers를 첫 번째 RegularExpressionModifiers일치한 소스 텍스트라고 하자.
  2. removeModifiers를 두 번째 RegularExpressionModifiers일치한 소스 텍스트라고 하자.
  3. modifiedRerUpdateModifiers(regexpRecord, CodePointsToString(addModifiers), CodePointsToString(removeModifiers))라고 하자.
  4. 인자 modifiedRerdirection으로 DisjunctionCompileSubpattern을 반환한다.
AtomEscape :: DecimalEscape
  1. nDecimalEscapeCapturingGroupNumber라고 하자.
  2. Assert: nregexpRecord.[[CapturingGroupsCount]].
  3. BackreferenceMatcher(regexpRecord, « n », direction)를 반환한다.
Note 3

형식 \ 뒤에 0이 아닌 십진수 n이 오는 escape sequence는 nth 캡처 괄호 집합의 결과(22.2.2.1)와 매치한다. 정규 표현식의 캡처 괄호가 n개보다 적으면 오류이다. 정규 표현식의 캡처 괄호가 n개 이상이지만 nth 것이 아무것도 캡처하지 않아 undefined이면, 역참조는 항상 성공한다.

AtomEscape :: CharacterEscape
  1. cvCharacterEscapeCharacterValue라고 하자.
  2. ch를 character value가 cv인 character라고 하자.
  3. charSet을 character ch를 포함하는 단일 요소 CharSet이라고 하자.
  4. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
AtomEscape :: CharacterClassEscape
  1. cs를 인자 regexpRecordCharacterClassEscapeCompileToCharSet이라고 하자.
  2. regexpRecord.[[UnicodeSets]]false이거나 cs의 모든 CharSetElement가 단일 character로 구성되어 있으면(cs가 비어 있는 경우 포함), CharacterSetMatcher(regexpRecord, cs, false, direction)를 반환한다.
  3. lmMatchers의 빈 List라고 하자.
  4. cs 안의 둘 이상의 character를 포함하는 각 CharSetElement s에 대해, 길이의 내림차순으로 반복하며, 다음을 수행한다.
    1. cs2s의 마지막 코드 포인트를 포함하는 단일 요소 CharSet이라고 하자.
    2. m2CharacterSetMatcher(regexpRecord, cs2, false, direction)라고 하자.
    3. s 안의 각 코드 포인트 c1에 대해, 그 끝에서 두 번째 코드 포인트부터 역순으로 반복하며, 다음을 수행한다.
      1. cs1c1을 포함하는 단일 요소 CharSet이라고 하자.
      2. m1CharacterSetMatcher(regexpRecord, cs1, false, direction)라고 하자.
      3. m2MatchSequence(m1, m2, direction)로 설정한다.
    4. m2lm에 추가한다.
  5. singles를 단일 character로 구성된 cs의 모든 CharSetElement를 포함하는 CharSet이라고 하자.
  6. CharacterSetMatcher(regexpRecord, singles, false, direction)를 lm에 추가한다.
  7. cs가 character들의 빈 시퀀스를 포함하면 EmptyMatcher()를 lm에 추가한다.
  8. m2lm의 마지막 Matcher라고 하자.
  9. lm의 각 Matcher m1에 대해, 끝에서 두 번째 요소부터 역순으로 반복하며, 다음을 수행한다.
    1. m2MatchTwoAlternatives(m1, m2)로 설정한다.
  10. m2를 반환한다.
AtomEscape :: k GroupName
  1. matchingGroupSpecifiersGroupSpecifiersThatMatch(GroupName)라고 하자.
  2. parenIndices를 새로운 빈 List라고 하자.
  3. matchingGroupSpecifiers의 각 GroupSpecifier groupSpecifier에 대해, 다음을 수행한다.
    1. parenIndexCountLeftCapturingParensBefore(groupSpecifier)라고 하자.
    2. parenIndexparenIndices에 추가한다.
  4. BackreferenceMatcher(regexpRecord, parenIndices, direction)를 반환한다.

22.2.2.7.1 CharacterSetMatcher ( regexpRecord, charSet, invert, direction )

The abstract operation CharacterSetMatcher takes arguments regexpRecord (a RegExp Record), charSet (a CharSet), invert (a Boolean), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]true이면,
    1. Assert: invertfalse이다.
    2. Assert: charSet의 모든 CharSetElement는 단일 character로 구성된다.
  2. regexpRecord, charSet, invert, 및 direction을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, c)를 가진 새로운 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. inputx.[[Input]]이라고 하자.
    4. endIndexx.[[EndIndex]]라고 하자.
    5. directionforward이면 fendIndex + 1이라고 하자.
    6. 그렇지 않으면, fendIndex - 1이라고 하자.
    7. inputLengthinput 안의 요소 개수라고 하자.
    8. f < 0이거나 f > inputLength이면 failure를 반환한다.
    9. indexmin(endIndex, f)라고 하자.
    10. ch를 character input[index]라고 하자.
    11. ccCanonicalize(regexpRecord, ch)라고 하자.
    12. Canonicalize(regexpRecord, a)가 cc인 정확히 하나의 character a를 포함하는 CharSetElementcharSet 안에 존재하면 foundtrue라고 하자; 그렇지 않으면 foundfalse라고 하자.
    13. invertfalse이고 foundfalse이면 failure를 반환한다.
    14. inverttrue이고 foundtrue이면 failure를 반환한다.
    15. capx.[[Captures]]라고 하자.
    16. yMatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: cap }라고 하자.
    17. c(y)를 반환한다.

22.2.2.7.2 BackreferenceMatcher ( regexpRecord, ns, direction )

The abstract operation BackreferenceMatcher takes arguments regexpRecord (a RegExp Record), ns (a List of positive integers), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. regexpRecord, ns, 및 direction을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, c)를 가진 새로운 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. inputx.[[Input]]이라고 하자.
    4. capx.[[Captures]]라고 하자.
    5. rundefined라고 하자.
    6. ns의 각 정수 n에 대해, 다음을 수행한다.
      1. cap[n]이 undefined가 아니면,
        1. Assert: rundefined이다.
        2. rcap[n]로 설정한다.
    7. rundefined이면 c(x)를 반환한다.
    8. endIndexx.[[EndIndex]]라고 하자.
    9. rsr.[[StartIndex]]라고 하자.
    10. rer.[[EndIndex]]라고 하자.
    11. lenre - rs라고 하자.
    12. directionforward이면 fendIndex + len이라고 하자.
    13. 그렇지 않으면, fendIndex - len이라고 하자.
    14. inputLengthinput 안의 요소 개수라고 하자.
    15. f < 0이거나 f > inputLength이면 failure를 반환한다.
    16. gmin(endIndex, f)라고 하자.
    17. 0(포함)부터 len(제외)까지의 구간에 있는 정수 iCanonicalize(regexpRecord, input[rs + i])가 Canonicalize(regexpRecord, input[g + i])가 아닌 것이 존재하면 failure를 반환한다.
    18. yMatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: cap }라고 하자.
    19. c(y)를 반환한다.

22.2.2.7.3 Canonicalize ( regexpRecord, ch )

The abstract operation Canonicalize takes arguments regexpRecord (a RegExp Record) and ch (a character) and returns a character. It performs the following steps when called:

  1. HasEitherUnicodeFlag(regexpRecord)가 true이고 regexpRecord.[[IgnoreCase]]true이면,
    1. Unicode Character Database의 파일 CaseFolding.txtch에 대해 simple 또는 common case folding 매핑을 제공하면, 그 매핑을 ch에 적용한 결과를 반환한다.
    2. ch를 반환한다.
  2. regexpRecord.[[IgnoreCase]]false이면 ch를 반환한다.
  3. Assert: ch는 UTF-16 코드 단위이다.
  4. cp를 수치 값이 ch의 수치 값인 코드 포인트라고 하자.
  5. u를 Unicode Default Case Conversion 알고리즘에 따른 toUppercase(« cp »)라고 하자.
  6. uStrCodePointsToString(u)라고 하자.
  7. uStr의 길이가 1이 아니면 ch를 반환한다.
  8. cuuStr의 단일 코드 단위 요소라고 하자.
  9. ch의 수치 값 ≥ 128이고 cu의 수치 값 < 128이면 ch를 반환한다.
  10. cu를 반환한다.
Note

HasEitherUnicodeFlag(regexpRecord)가 true인 대소문자 비구분 매치에서는, 모든 character가 비교되기 직전에 Unicode Standard가 제공하는 simple 매핑을 사용해 암묵적으로 case-fold된다. simple 매핑은 항상 단일 코드 포인트로 매핑하므로, 예를 들어 ß (U+00DF LATIN SMALL LETTER SHARP S)를 ssSS로 매핑하지 않는다. 그러나 Basic Latin 블록 밖의 코드 포인트를 그 안의 코드 포인트로 매핑할 수는 있다. 예를 들어, ſ (U+017F LATIN SMALL LETTER LONG S)는 s (U+0073 LATIN SMALL LETTER S)로 case-fold되고 (U+212A KELVIN SIGN)는 k (U+006B LATIN SMALL LETTER K)로 case-fold된다. 이러한 코드 포인트를 포함하는 String들은 /[a-z]/ui와 같은 정규 표현식에 의해 매치된다.

HasEitherUnicodeFlag(regexpRecord)가 false인 대소문자 비구분 매치에서는, 매핑이 toCasefold가 아니라 Unicode Default Case Conversion 알고리즘 toUppercase에 기반하므로 몇 가지 미묘한 차이가 생긴다. 예를 들어, (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"와 같은 String은 /[a-z]/i에 매치되지 않는다.

22.2.2.7.4 UpdateModifiers ( regexpRecord, add, remove )

The abstract operation UpdateModifiers takes arguments regexpRecord (a RegExp Record), add (a String), and remove (a String) and returns a RegExp Record. It performs the following steps when called:

  1. Assert: addremove는 공통 요소를 가지지 않는다.
  2. ignoreCaseregexpRecord.[[IgnoreCase]]라고 하자.
  3. multilineregexpRecord.[[Multiline]]이라고 하자.
  4. dotAllregexpRecord.[[DotAll]]이라고 하자.
  5. unicoderegexpRecord.[[Unicode]]라고 하자.
  6. unicodeSetsregexpRecord.[[UnicodeSets]]라고 하자.
  7. capturingGroupsCountregexpRecord.[[CapturingGroupsCount]]라고 하자.
  8. remove"i"를 포함하면 ignoreCasefalse로 설정한다.
  9. 그렇지 않고 add"i"를 포함하면 ignoreCasetrue로 설정한다.
  10. remove"m"을 포함하면 multilinefalse로 설정한다.
  11. 그렇지 않고 add"m"을 포함하면 multilinetrue로 설정한다.
  12. remove"s"를 포함하면 dotAllfalse로 설정한다.
  13. 그렇지 않고 add"s"를 포함하면 dotAlltrue로 설정한다.
  14. RegExp Record { [[IgnoreCase]]: ignoreCase, [[Multiline]]: multiline, [[DotAll]]: dotAll, [[Unicode]]: unicode, [[UnicodeSets]]: unicodeSets, [[CapturingGroupsCount]]: capturingGroupsCount }를 반환한다.

22.2.2.8 Runtime Semantics: CompileCharacterClass

The syntax-directed operation CompileCharacterClass takes argument regexpRecord (a RegExp Record) and returns a Record with fields [[CharSet]] (a CharSet) and [[Invert]] (a Boolean). It is defined piecewise over the following productions:

CharacterClass :: [ ClassContents ]
  1. charSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  2. Record { [[CharSet]]: charSet, [[Invert]]: false }를 반환한다.
CharacterClass :: [^ ClassContents ]
  1. charSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  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

The syntax-directed operation CompileToCharSet takes argument regexpRecord (a RegExp Record) and returns a CharSet.

Note 1

이 절은 B.1.2.8에서 수정된다.

It is defined piecewise over the following productions:

ClassContents :: [empty]
  1. CharSet을 반환한다.
NonemptyClassRanges :: ClassAtom NonemptyClassRangesNoDash
  1. charSet을 인자 regexpRecordClassAtomCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordNonemptyClassRangesNoDashCompileToCharSet이라고 하자.
  3. CharSet charSetotherSet의 합집합을 반환한다.
NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. charSet을 인자 regexpRecord로 첫 번째 ClassAtomCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecord로 두 번째 ClassAtomCompileToCharSet이라고 하자.
  3. remainingSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  4. rangeSetCharacterRange(charSet, otherSet)라고 하자.
  5. rangeSetremainingSet의 합집합을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash NonemptyClassRangesNoDash
  1. charSet을 인자 regexpRecordClassAtomNoDashCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordNonemptyClassRangesNoDashCompileToCharSet이라고 하자.
  3. CharSet charSetotherSet의 합집합을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. charSet을 인자 regexpRecordClassAtomNoDashCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordClassAtomCompileToCharSet이라고 하자.
  3. remainingSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  4. rangeSetCharacterRange(charSet, otherSet)라고 하자.
  5. rangeSetremainingSet의 합집합을 반환한다.
Note 2

ClassContents는 단일 ClassAtom 및/또는 대시로 구분된 두 ClassAtom의 범위로 전개될 수 있다. 후자의 경우 ClassContents는 첫 번째 ClassAtom과 두 번째 ClassAtom 사이의 모든 character를 포함하며, 양 끝도 포함한다; 어느 ClassAtom이 단일 character를 나타내지 않거나(예를 들어, 하나가 \w인 경우) 첫 번째 ClassAtom의 character value가 두 번째 ClassAtom의 character value보다 엄격히 크면 오류가 발생한다.

Note 3

패턴이 대소문자를 무시하더라도, 범위의 두 끝의 대소문자는 어떤 character가 그 범위에 속하는지 결정하는 데 중요하다. 따라서 예를 들어, 패턴 /[E-F]/i는 문자 E, F, e, f에만 매치하는 반면, 패턴 /[E-f]/i는 Unicode Basic Latin 블록의 모든 대문자와 소문자뿐만 아니라 기호 [, \, ], ^, _, 및 `에도 매치한다.

Note 4

- character는 리터럴로 취급될 수도 있고 범위를 나타낼 수도 있다. ClassContents의 첫 번째 또는 마지막 character이거나, 범위 지정의 시작 또는 끝 한계이거나, 범위 지정 바로 뒤에 오면 리터럴로 취급된다.

ClassAtom :: -
  1. 단일 character - U+002D (HYPHEN-MINUS)를 포함하는 CharSet을 반환한다.
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. SourceCharacter와 일치한 character를 포함하는 CharSet을 반환한다.
ClassEscape :: b - CharacterEscape
  1. cv를 이 ClassEscapeCharacterValue라고 하자.
  2. c를 character value가 cv인 character라고 하자.
  3. 단일 character c를 포함하는 CharSet을 반환한다.
Note 5

ClassAtom\b, \B, 및 역참조를 제외하고 정규 표현식의 나머지에서 허용되는 어떤 escape sequence든 사용할 수 있다. CharacterClass 안에서 \b는 백스페이스 character를 의미하고, \B와 역참조는 오류를 일으킨다. ClassAtom 안에서 역참조를 사용하면 오류가 발생한다.

CharacterClassEscape :: d
  1. character 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 생성식의 오른쪽에 있는 코드 포인트에 대응하는 모든 character를 포함하는 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. 인자 regexpRecordUnicodePropertyValueExpressionCompileToCharSet을 반환한다.
CharacterClassEscape :: P{ UnicodePropertyValueExpression }
  1. charSet을 인자 regexpRecordUnicodePropertyValueExpressionCompileToCharSet이라고 하자.
  2. Assert: charSet은 단일 코드 포인트만 포함한다.
  3. CharacterComplement(regexpRecord, charSet)를 반환한다.
UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  1. psUnicodePropertyName일치한 소스 텍스트라고 하자.
  2. pUnicodeMatchProperty(regexpRecord, ps)라고 하자.
  3. Assert: pTable 64의 “Property name and aliases” 열에 나열된 Unicode property name 또는 property alias이다.
  4. vsUnicodePropertyValue일치한 소스 텍스트라고 하자.
  5. vUnicodeMatchPropertyValue(p, vs)라고 하자.
  6. charSet을 character database 정의가 값 v를 가진 속성 p를 포함하는 모든 Unicode 코드 포인트를 포함하는 CharSet이라고 하자.
  7. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. sLoneUnicodePropertyNameOrValue일치한 소스 텍스트라고 하자.
  2. UnicodeMatchPropertyValue(General_Category, s)가 PropertyValueAliases.txt에 나열된 General_Category (gc) 속성에 대한 Unicode property value 또는 property value alias이면,
    1. character database 정의가 값 s를 가진 속성 “General_Category”를 포함하는 모든 Unicode 코드 포인트를 포함하는 CharSet을 반환한다.
  3. pUnicodeMatchProperty(regexpRecord, s)라고 하자.
  4. Assert: pTable 65의 “Property name and aliases” 열에 나열된 이진 Unicode 속성 또는 이진 속성 별칭이거나, Table 66의 “Property name” 열에 나열된 문자열의 이진 Unicode 속성이다.
  5. charSet을 character database 정의가 값 “True”를 가진 속성 p를 포함하는 모든 CharSetElement를 포함하는 CharSet이라고 하자.
  6. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassUnion :: ClassSetRange ClassUnionopt
  1. charSet을 인자 regexpRecordClassSetRangeCompileToCharSet이라고 하자.
  2. ClassUnion이 존재하면,
    1. otherSet을 인자 regexpRecordClassUnionCompileToCharSet이라고 하자.
    2. CharSet charSetotherSet의 합집합을 반환한다.
  3. charSet을 반환한다.
ClassUnion :: ClassSetOperand ClassUnionopt
  1. charSet을 인자 regexpRecordClassSetOperandCompileToCharSet이라고 하자.
  2. ClassUnion이 존재하면,
    1. otherSet을 인자 regexpRecordClassUnionCompileToCharSet이라고 하자.
    2. CharSet charSetotherSet의 합집합을 반환한다.
  3. charSet을 반환한다.
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. charSet을 인자 regexpRecord로 첫 번째 ClassSetOperandCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecord로 두 번째 ClassSetOperandCompileToCharSet이라고 하자.
  3. CharSet charSetotherSet의 교집합을 반환한다.
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. charSet을 인자 regexpRecordClassIntersectionCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordClassSetOperandCompileToCharSet이라고 하자.
  3. CharSet charSetotherSet의 교집합을 반환한다.
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. charSet을 인자 regexpRecord로 첫 번째 ClassSetOperandCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecord로 두 번째 ClassSetOperandCompileToCharSet이라고 하자.
  3. otherSetCharSetElement이기도 하지 않은 charSetCharSetElement를 포함하는 CharSet을 반환한다.
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. charSet을 인자 regexpRecordClassSubtractionCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordClassSetOperandCompileToCharSet이라고 하자.
  3. otherSetCharSetElement이기도 하지 않은 charSetCharSetElement를 포함하는 CharSet을 반환한다.
ClassSetRange :: ClassSetCharacter - ClassSetCharacter
  1. charSet을 인자 regexpRecord로 첫 번째 ClassSetCharacterCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecord로 두 번째 ClassSetCharacterCompileToCharSet이라고 하자.
  3. MaybeSimpleCaseFolding(regexpRecord, CharacterRange(charSet, otherSet))를 반환한다.
Note 6

결과는 종종 둘 이상의 범위로 구성된다. UnicodeSets가 true이고 IgnoreCase가 true이면, MaybeSimpleCaseFolding(regexpRecord, [Ā-č])는 그 범위의 홀수 번호 코드 포인트만 포함한다.

ClassSetOperand :: ClassSetCharacter
  1. charSet을 인자 regexpRecordClassSetCharacterCompileToCharSet이라고 하자.
  2. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassSetOperand :: ClassStringDisjunction
  1. charSet을 인자 regexpRecordClassStringDisjunctionCompileToCharSet이라고 하자.
  2. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassSetOperand :: NestedClass
  1. 인자 regexpRecordNestedClassCompileToCharSet을 반환한다.
NestedClass :: [ ClassContents ]
  1. 인자 regexpRecordClassContentsCompileToCharSet을 반환한다.
NestedClass :: [^ ClassContents ]
  1. charSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
NestedClass :: \ CharacterClassEscape
  1. 인자 regexpRecordCharacterClassEscapeCompileToCharSet을 반환한다.
ClassStringDisjunction :: \q{ ClassStringDisjunctionContents }
  1. 인자 regexpRecordClassStringDisjunctionContentsCompileToCharSet을 반환한다.
ClassStringDisjunctionContents :: ClassString
  1. s를 인자 regexpRecordClassStringCompileClassSetString이라고 하자.
  2. 하나의 string s를 포함하는 CharSet을 반환한다.
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. s를 인자 regexpRecordClassStringCompileClassSetString이라고 하자.
  2. charSet을 하나의 string s를 포함하는 CharSet이라고 하자.
  3. otherSet을 인자 regexpRecordClassStringDisjunctionContentsCompileToCharSet이라고 하자.
  4. CharSet charSetotherSet의 합집합을 반환한다.
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape \ ClassSetReservedPunctuator
  1. cv를 이 ClassSetCharacterCharacterValue라고 하자.
  2. c를 character value가 cv인 character라고 하자.
  3. 단일 character c를 포함하는 CharSet을 반환한다.
ClassSetCharacter :: \b
  1. 단일 character U+0008 (BACKSPACE)를 포함하는 CharSet을 반환한다.

22.2.2.9.1 CharacterRange ( charSet, otherSet )

The abstract operation CharacterRange takes arguments charSet (a CharSet) and otherSet (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. Assert: charSetotherSet은 각각 정확히 하나의 character를 포함한다.
  2. aCharSet charSet 안의 하나의 character라고 하자.
  3. bCharSet otherSet 안의 하나의 character라고 하자.
  4. i를 character a의 character value라고 하자.
  5. j를 character b의 character value라고 하자.
  6. Assert: ij.
  7. i부터 j까지의 포함 구간에 있는 character value를 가진 모든 character를 포함하는 CharSet을 반환한다.

22.2.2.9.2 HasEitherUnicodeFlag ( regexpRecord )

The abstract operation HasEitherUnicodeFlag takes argument regexpRecord (a RegExp Record) and returns a Boolean. It performs the following steps when called:

  1. regexpRecord.[[Unicode]]true이거나 regexpRecord.[[UnicodeSets]]true이면 true를 반환한다.
  2. false를 반환한다.

22.2.2.9.3 WordCharacters ( regexpRecord )

The abstract operation WordCharacters takes argument regexpRecord (a RegExp Record) and returns a CharSet. \b, \B, \w, 및 \W의 목적상 "word characters"로 간주되는 character들을 포함하는 CharSet을 반환한다. It performs the following steps when called:

  1. basicWordChars를 ASCII word characters 안의 모든 character를 포함하는 CharSet이라고 하자.
  2. extraWordCharsbasicWordChars 안에 없지만 Canonicalize(regexpRecord, c)가 basicWordChars 안에 있는 모든 character c를 포함하는 CharSet이라고 하자.
  3. Assert: HasEitherUnicodeFlag(regexpRecord)가 true이고 regexpRecord.[[IgnoreCase]]true인 경우가 아니면 extraWordChars는 비어 있다.
  4. basicWordCharsextraWordChars의 합집합을 반환한다.

22.2.2.9.4 AllCharacters ( regexpRecord )

The abstract operation AllCharacters takes argument regexpRecord (a RegExp Record) and returns a CharSet. 정규 표현식 플래그에 따른 “all characters”의 집합을 반환한다. It performs the following steps when called:

  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 )

The abstract operation MaybeSimpleCaseFolding takes arguments regexpRecord (a RegExp Record) and charSet (a CharSet) and returns a CharSet. regexpRecord.[[UnicodeSets]]false이거나 regexpRecord.[[IgnoreCase]]false이면, charSet을 반환한다. 그렇지 않으면, Unicode Character Database의 파일 CaseFolding.txt에 있는 Simple Case Folding (scf(cp)) 정의(각각 단일 코드 포인트를 다른 단일 코드 포인트로 매핑함)를 사용하여 charSet의 각 CharSetElement를 character별로 정준 형식으로 매핑하고, 그 결과 CharSet을 반환한다. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]false이거나 regexpRecord.[[IgnoreCase]]false이면 charSet을 반환한다.
  2. otherSet을 새로운 빈 CharSet이라고 하자.
  3. charSet의 각 CharSetElement s에 대해, 다음을 수행한다.
    1. t를 빈 character 시퀀스라고 하자.
    2. s 안의 각 단일 코드 포인트 cp에 대해, 다음을 수행한다.
      1. scf(cp)를 t에 추가한다.
    3. totherSet에 추가한다.
  4. otherSet을 반환한다.

22.2.2.9.6 CharacterComplement ( regexpRecord, complement )

The abstract operation CharacterComplement takes arguments regexpRecord (a RegExp Record) and complement (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. charSetAllCharacters(regexpRecord)라고 하자.
  2. complementCharSetElement이기도 하지 않은 charSetCharSetElement를 포함하는 CharSet을 반환한다.

22.2.2.9.7 UnicodeMatchProperty ( regexpRecord, p )

The abstract operation UnicodeMatchProperty takes arguments regexpRecord (a RegExp Record) and p (ECMAScript source text) and returns a Unicode property name. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]true이고 pTable 66의 “Property name” 열에 나열된 Unicode property name이면,
    1. Unicode 코드 포인트의 List p를 반환한다.
  2. Assert: pTable 64 또는 Table 65의 “Property name and aliases” 열에 나열된 Unicode property name 또는 property alias이다.
  3. c를 해당 행의 “Canonical property name” 열에 주어진 p의 정준 property name이라고 하자.
  4. Unicode 코드 포인트의 List c를 반환한다.

구현은 Table 64, Table 65, 및 Table 66에 나열된 Unicode property names와 별칭을 지원해야 한다. 상호 운용성을 보장하기 위해, 구현은 다른 어떤 property names나 별칭도 지원해서는 안 된다.

Note 1

예를 들어, Script_Extensions(property name)와 scx(property alias)는 유효하지만, script_extensionsScx는 유효하지 않다.

Note 2

나열된 속성들은 UTS18 RL1.2가 요구하는 것의 상위 집합을 형성한다.

Note 3

이 표들에 있는 항목들의 철자(대소문자 포함)는 Unicode Character Database의 파일 PropertyAliases.txt에서 사용되는 철자와 일치한다. 그 파일의 정확한 철자는 안정적으로 보장된다.

Table 64: 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
Table 65: 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
Table 66: 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 )

The abstract operation UnicodeMatchPropertyValue takes arguments p (ECMAScript source text) and v (ECMAScript source text) and returns a Unicode property value. It performs the following steps when called:

  1. Assert: pTable 64의 “Canonical property name” 열에 나열된 정준적이고 별칭이 아닌 Unicode property name이다.
  2. Assert: vPropertyValueAliases.txt에 나열된 Unicode 속성 p에 대한 property value 또는 property value alias이다.
  3. value를 해당 행의 “Canonical property value” 열에 주어진 v의 정준 속성 값이라고 하자.
  4. Unicode 코드 포인트의 List value를 반환한다.

구현은 Table 64에 나열된 속성에 대해 PropertyValueAliases.txt에 나열된 Unicode 속성 값과 속성 값 별칭을 지원해야 한다. 상호 운용성을 보장하기 위해, 구현은 다른 어떤 속성 값이나 속성 값 별칭도 지원해서는 안 된다.

Note 1

예를 들어, XpeoOld_Persian은 유효한 Script_Extensions 값이지만, xpeoOld Persian은 유효하지 않다.

Note 2

이 알고리즘은 UAX44에 나열된 symbolic values에 대한 매칭 규칙과 다르다: 대소문자, white space, U+002D (HYPHEN-MINUS), 및 U+005F (LOW LINE)는 무시되지 않으며, Is 접두사는 지원되지 않는다.

22.2.2.10 Runtime Semantics: CompileClassSetString

The syntax-directed operation CompileClassSetString takes argument regexpRecord (a RegExp Record) and returns a sequence of characters. It is defined piecewise over the following productions:

ClassString :: [empty]
  1. 빈 character 시퀀스를 반환한다.
ClassString :: NonEmptyClassString
  1. 인자 regexpRecordNonEmptyClassStringCompileClassSetString을 반환한다.
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. cs를 인자 regexpRecordClassSetCharacterCompileToCharSet이라고 하자.
  2. s1cs의 단일 CharSetElement인 character 시퀀스라고 하자.
  3. NonEmptyClassString이 존재하면,
    1. s2를 인자 regexpRecordNonEmptyClassStringCompileClassSetString이라고 하자.
    2. s1s2의 연결을 반환한다.
  4. s1을 반환한다.

22.2.3 RegExp 생성을 위한 추상 연산

22.2.3.1 RegExpCreate ( pattern, flags )

The abstract operation RegExpCreate takes arguments pattern (an ECMAScript language value) and flags (a String or undefined) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. obj를 ! RegExpAlloc(%RegExp%)라고 하자.
  2. RegExpInitialize(obj, pattern, flags)를 반환한다.

22.2.3.2 RegExpAlloc ( newTarget )

The abstract operation RegExpAlloc takes argument newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  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 )

The abstract operation RegExpInitialize takes arguments obj (an Object), pattern (an ECMAScript language value), and flags (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. patternundefined이면, pattern을 빈 String으로 설정한다.
  2. 그렇지 않으면, pattern을 ? ToString(pattern)으로 설정한다.
  3. flagsundefined이면, flags를 빈 String으로 설정한다.
  4. 그렇지 않으면, flags를 ? ToString(flags)로 설정한다.
  5. flags"d", "g", "i", "m", "s", "u", "v", 또는 "y"가 아닌 코드 단위를 포함하면, SyntaxError 예외를 던진다.
  6. flags가 어떤 코드 단위든 두 번 이상 포함하면, SyntaxError 예외를 던진다.
  7. flags"i"를 포함하면 itrue라고 하자; 그렇지 않으면 ifalse라고 하자.
  8. flags"m"을 포함하면 mtrue라고 하자; 그렇지 않으면 mfalse라고 하자.
  9. flags"s"를 포함하면 strue라고 하자; 그렇지 않으면 sfalse라고 하자.
  10. flags"u"를 포함하면 utrue라고 하자; 그렇지 않으면 ufalse라고 하자.
  11. flags"v"를 포함하면 vtrue라고 하자; 그렇지 않으면 vfalse라고 하자.
  12. utrue이거나 vtrue이면,
    1. patternTextStringToCodePoints(pattern)라고 하자.
  13. 그렇지 않으면,
    1. patternTextpattern의 각 16비트 요소를 Unicode BMP 코드 포인트로 해석한 결과라고 하자. UTF-16 디코딩은 그 요소들에 적용되지 않는다.
  14. parseResultParsePattern(patternText, u, v)라고 하자.
  15. parseResultSyntaxError 객체들의 비어 있지 않은 List이면, SyntaxError 예외를 던진다.
  16. Assert: parseResultPattern Parse Node이다.
  17. obj.[[OriginalSource]]pattern으로 설정한다.
  18. obj.[[OriginalFlags]]flags로 설정한다.
  19. capturingGroupsCountCountLeftCapturingParensWithin(parseResult)라고 하자.
  20. regexpRecordRegExp Record { [[IgnoreCase]]: i, [[Multiline]]: m, [[DotAll]]: s, [[Unicode]]: u, [[UnicodeSets]]: v, [[CapturingGroupsCount]]: capturingGroupsCount }라고 하자.
  21. obj.[[RegExpRecord]]regexpRecord로 설정한다.
  22. obj.[[RegExpMatcher]]를 인자 regexpRecordparseResultCompilePattern으로 설정한다.
  23. Set(obj, "lastIndex", +0𝔽, true)를 수행한다.
  24. obj를 반환한다.

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

The abstract operation ParsePattern takes arguments patternText (a sequence of Unicode code points), u (a Boolean), and v (a Boolean) and returns a Parse Node or a non-empty List of SyntaxError objects.

Note

이 절은 B.1.2.9에서 수정된다.

It performs the following steps when called:

  1. vtrue이고 utrue이면,
    1. parseResult를 하나 이상의 SyntaxError 객체를 포함하는 List라고 하자.
  2. 그렇지 않고 vtrue이면,
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups])라고 하자.
  3. 그렇지 않고 utrue이면,
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])라고 하자.
  4. 그렇지 않으면,
    1. parseResultParseText(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. patternIsRegExptrue이고 flagsundefined이면,
      1. patternConstructor를 ? Get(patternOrRegexp, "constructor")라고 하자.
      2. SameValue(newTarget, patternConstructor)가 true이면 patternOrRegexp를 반환한다.
  3. 그렇지 않으면,
    1. newTarget을 NewTarget이라고 하자.
  4. patternOrRegexp가 Object이고 [[RegExpMatcher]] 내부 슬롯을 가지면,
    1. patternSourcepatternOrRegexp.[[OriginalSource]]라고 하자.
    2. flagsundefined이면, flagspatternOrRegexp.[[OriginalFlags]]로 설정한다.
  5. 그렇지 않고 patternIsRegExptrue이면,
    1. patternSource를 ? Get(patternOrRegexp, "source")라고 하자.
    2. flagsundefined이면,
      1. flags를 ? Get(patternOrRegexp, "flags")로 설정한다.
  6. 그렇지 않으면,
    1. patternSourcepatternOrRegexp라고 하자.
  7. obj를 ? RegExpAlloc(newTarget)라고 하자.
  8. RegExpInitialize(obj, patternSource, flags)를 반환한다.
Note

pattern이 StringLiteral을 사용해 제공되면, String이 이 함수에 의해 처리되기 전에 일반적인 escape sequence 치환이 수행된다. pattern이 이 함수에 의해 인식되어야 하는 escape sequence를 포함해야 하는 경우, StringLiteral의 내용이 형성될 때 U+005C (REVERSE SOLIDUS) 코드 포인트가 제거되지 않도록 StringLiteral 안에서 escape되어야 한다.

22.2.5 RegExp 생성자의 속성

RegExp 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

22.2.5.1 RegExp.escape ( str )

이 함수는 정규 표현식 Pattern에서 잠재적으로 특별한 문자들이 동등한 escape sequence로 대체된 str의 사본을 반환한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. str이 String이 아니면, TypeError 예외를 던진다.
  2. escaped를 빈 String이라고 하자.
  3. cpListStringToCodePoints(str)라고 하자.
  4. cpList의 각 코드 포인트 cp에 대해, 다음을 수행한다.
    1. escaped가 빈 String이고 cpDecimalDigit 또는 AsciiLetter 중 하나와 일치하면,
      1. NOTE: 선행 숫자를 escape하면 출력이 \0 문자 escape 또는 \1과 같은 DecimalEscape 뒤에서 사용될 수 있는 패턴 텍스트와 대응하며, 앞선 escape sequence의 확장으로 해석되지 않고 여전히 str과 매치되도록 보장한다. 선행 ASCII 문자를 escape하는 것은 \c 뒤의 문맥에 대해 같은 일을 한다.
      2. numericValuecp의 수치 값이라고 하자.
      3. hexNumber::toString(𝔽(numericValue), 16)이라고 하자.
      4. Assert: hex의 길이는 2이다.
      5. escaped를 코드 단위 0x005C (REVERSE SOLIDUS), "x", 및 hex의 문자열 연결로 설정한다.
    2. 그렇지 않으면,
      1. escapedescapedEncodeForRegExpEscape(cp)의 문자열 연결로 설정한다.
  5. escaped를 반환한다.
Note

이름이 비슷하지만, EscapeRegExpPatternRegExp.escape는 비슷한 동작을 수행하지 않는다. 전자는 문자열로 표현하기 위해 패턴을 escape하는 반면, 이 함수는 패턴 안에서 표현하기 위해 문자열을 escape한다.

22.2.5.1.1 EncodeForRegExpEscape ( cp )

The abstract operation EncodeForRegExpEscape takes argument cp (a code point) and returns a String. 이 연산은 cp와 매치하기 위한 Pattern을 나타내는 String을 반환한다. cp가 공백 문자이거나 ASCII 구두점이면, 반환값은 escape sequence이다. 그렇지 않으면, 반환값은 cp 자체의 String 표현이다. It performs the following steps when called:

  1. cpSyntaxCharacter와 일치하거나 cp가 U+002F (SOLIDUS)이면,
    1. 0x005C (REVERSE SOLIDUS)와 UTF16EncodeCodePoint(cp)의 문자열 연결을 반환한다.
  2. cpTable 62의 “Code Point” 열에 나열된 코드 포인트이면,
    1. 0x005C (REVERSE SOLIDUS)와 “Code Point” 열이 cp를 포함하는 행의 “ControlEscape” 열에 있는 문자열의 문자열 연결을 반환한다.
  3. otherPunctuators",-=<>#&!%:;@~'`"와 코드 단위 0x0022 (QUOTATION MARK)의 문자열 연결이라고 하자.
  4. toEscapeStringToCodePoints(otherPunctuators)라고 하자.
  5. toEscapecp를 포함하거나, cpWhiteSpace 또는 LineTerminator 중 하나와 일치하거나, cp가 선행 서로게이트 또는 후행 서로게이트와 같은 수치 값을 가지면,
    1. cpNumcp의 수치 값이라고 하자.
    2. cpNum ≤ 0xFF이면,
      1. hexNumber::toString(𝔽(cpNum), 16)이라고 하자.
      2. 코드 단위 0x005C (REVERSE SOLIDUS), "x", 및 StringPad(hex, 2, "0", start)의 문자열 연결을 반환한다.
    3. escaped를 빈 String이라고 하자.
    4. codeUnitsUTF16EncodeCodePoint(cp)라고 하자.
    5. codeUnits의 각 코드 단위 cu에 대해, 다음을 수행한다.
      1. escapedescapedUnicodeEscape(cu)의 문자열 연결로 설정한다.
    6. escaped를 반환한다.
  6. UTF16EncodeCodePoint(cp)를 반환한다.

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 값을 반환한다.

이 함수의 "name" 속성의 값은 "get [Symbol.species]"이다.

Note

RegExp 프로토타입 메서드는 보통 자신의 this 값의 생성자를 사용해 파생 객체를 생성한다. 그러나 서브클래스 생성자는 자신의 %Symbol.species% 속성을 재정의하여 그 기본 동작을 재정의할 수 있다.

22.2.6 RegExp 프로토타입 객체의 속성

RegExp 프로토타입 객체는:

  • %RegExp.prototype%이다.
  • 보통 객체이다.
  • RegExp 인스턴스가 아니며 [[RegExpMatcher]] 내부 슬롯이나 RegExp 인스턴스 객체의 다른 어떤 내부 슬롯도 가지지 않는다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
Note

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. regexpthis 값이라고 하자.
  2. RequireInternalSlot(regexp, [[RegExpMatcher]])를 수행한다.
  3. str을 ? ToString(string)이라고 하자.
  4. RegExpBuiltinExec(regexp, str)를 반환한다.

22.2.6.3 get RegExp.prototype.dotAll

RegExp.prototype.dotAll은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0073 (LATIN SMALL LETTER S)이라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.4 get RegExp.prototype.flags

RegExp.prototype.flags는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. codeUnits를 새로운 빈 List라고 하자.
  4. hasIndicesToBoolean(? Get(regexp, "hasIndices"))라고 하자.
  5. hasIndicestrue이면, 코드 단위 0x0064 (LATIN SMALL LETTER D)를 codeUnits에 추가한다.
  6. globalToBoolean(? Get(regexp, "global"))이라고 하자.
  7. globaltrue이면, 코드 단위 0x0067 (LATIN SMALL LETTER G)를 codeUnits에 추가한다.
  8. ignoreCaseToBoolean(? Get(regexp, "ignoreCase"))라고 하자.
  9. ignoreCasetrue이면, 코드 단위 0x0069 (LATIN SMALL LETTER I)를 codeUnits에 추가한다.
  10. multilineToBoolean(? Get(regexp, "multiline"))이라고 하자.
  11. multilinetrue이면, 코드 단위 0x006D (LATIN SMALL LETTER M)를 codeUnits에 추가한다.
  12. dotAllToBoolean(? Get(regexp, "dotAll"))이라고 하자.
  13. dotAlltrue이면, 코드 단위 0x0073 (LATIN SMALL LETTER S)를 codeUnits에 추가한다.
  14. unicodeToBoolean(? Get(regexp, "unicode"))라고 하자.
  15. unicodetrue이면, 코드 단위 0x0075 (LATIN SMALL LETTER U)를 codeUnits에 추가한다.
  16. unicodeSetsToBoolean(? Get(regexp, "unicodeSets"))라고 하자.
  17. unicodeSetstrue이면, 코드 단위 0x0076 (LATIN SMALL LETTER V)를 codeUnits에 추가한다.
  18. stickyToBoolean(? Get(regexp, "sticky"))라고 하자.
  19. stickytrue이면, 코드 단위 0x0079 (LATIN SMALL LETTER Y)를 codeUnits에 추가한다.
  20. 코드 단위가 List codeUnits의 요소인 String 값을 반환한다. codeUnits가 요소를 가지지 않으면, 빈 String이 반환된다.

22.2.6.4.1 RegExpHasFlag ( regexp, codeUnit )

The abstract operation RegExpHasFlag takes arguments regexp (an ECMAScript language value) and codeUnit (a code unit) and returns either a normal completion containing either a Boolean or undefined, or a throw completion. It performs the following steps when called:

  1. regexp가 Object가 아니면, TypeError 예외를 던진다.
  2. regexp[[OriginalFlags]] 내부 슬롯을 가지지 않으면,
    1. SameValue(regexp, %RegExp.prototype%)가 true이면, undefined를 반환한다.
    2. TypeError 예외를 던진다.
  3. flagsregexp.[[OriginalFlags]]라고 하자.
  4. flagscodeUnit을 포함하면, true를 반환한다.
  5. false를 반환한다.

22.2.6.5 get RegExp.prototype.global

RegExp.prototype.global은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0067 (LATIN SMALL LETTER G)이라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.6 get RegExp.prototype.hasIndices

RegExp.prototype.hasIndices는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0064 (LATIN SMALL LETTER D)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.7 get RegExp.prototype.ignoreCase

RegExp.prototype.ignoreCase는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0069 (LATIN SMALL LETTER I)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  5. flags"g"를 포함하지 않으면, ? RegExpExec(regexp, str)를 반환한다.
  6. flags"u"를 포함하거나 flags"v"를 포함하면 fullUnicodetrue라고 하자; 그렇지 않으면 fullUnicodefalse라고 하자.
  7. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  8. array를 ! ArrayCreate(0)이라고 하자.
  9. matchCount를 0이라고 하자.
  10. 반복한다,
    1. result를 ? RegExpExec(regexp, str)라고 하자.
    2. resultnull이면,
      1. matchCount = 0이면, null을 반환한다.
      2. array를 반환한다.
    3. matchStr을 ? ToString(? Get(result, "0"))라고 하자.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(matchCount)), matchStr)를 수행한다.
    5. matchStr이 빈 String이면,
      1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))라고 하자.
      2. nextIndexAdvanceStringIndex(str, thisIndex, fullUnicode)라고 하자.
      3. Set(regexp, "lastIndex", 𝔽(nextIndex), true)를 수행한다.
    6. matchCountmatchCount + 1로 설정한다.

이 메서드의 "name" 속성의 값은 "[Symbol.match]"이다.

Note

%Symbol.match% 속성은 정규 표현식의 기본 동작을 가진 객체를 식별하기 위해 IsRegExp 추상 연산에서 사용된다. %Symbol.match% 속성이 없거나, 그러한 속성이 존재하지만 그 값이 Boolean으로 강제 변환될 때 true가 아닌 경우, 그 객체가 정규 표현식 객체로 사용되도록 의도되지 않았음을 나타낸다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. speciesConstructor를 ? SpeciesConstructor(regexp, %RegExp%)라고 하자.
  5. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  6. matcher를 ? Construct(speciesConstructor, « regexp, flags »)라고 하자.
  7. lastIndex를 ? ToLength(? Get(regexp, "lastIndex"))라고 하자.
  8. Set(matcher, "lastIndex", lastIndex, true)를 수행한다.
  9. flags"g"를 포함하면, globaltrue라고 하자.
  10. 그렇지 않으면, globalfalse라고 하자.
  11. flags"u"를 포함하거나 flags"v"를 포함하면, fullUnicodetrue라고 하자.
  12. 그렇지 않으면, fullUnicodefalse라고 하자.
  13. CreateRegExpStringIterator(matcher, str, global, fullUnicode)를 반환한다.

이 메서드의 "name" 속성의 값은 "[Symbol.matchAll]"이다.

22.2.6.10 get RegExp.prototype.multiline

RegExp.prototype.multiline은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x006D (LATIN SMALL LETTER M)이라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. lengthSstr의 길이라고 하자.
  5. functionalReplaceIsCallable(replaceValue)라고 하자.
  6. functionalReplacefalse이면,
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  7. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  8. flags"g"를 포함하면 globaltrue라고 하자; 그렇지 않으면 globalfalse라고 하자.
  9. globaltrue이면,
    1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  10. results를 새로운 빈 List라고 하자.
  11. donefalse라고 하자.
  12. donefalse인 동안 반복한다,
    1. result를 ? RegExpExec(regexp, str)라고 하자.
    2. resultnull이면,
      1. donetrue로 설정한다.
    3. 그렇지 않으면,
      1. resultresults에 추가한다.
      2. globalfalse이면,
        1. donetrue로 설정한다.
      3. 그렇지 않으면,
        1. matchStr을 ? ToString(? Get(result, "0"))라고 하자.
        2. matchStr이 빈 String이면,
          1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))라고 하자.
          2. flags"u"를 포함하거나 flags"v"를 포함하면 fullUnicodetrue라고 하자; 그렇지 않으면 fullUnicodefalse라고 하자.
          3. nextIndexAdvanceStringIndex(str, thisIndex, fullUnicode)라고 하자.
          4. Set(regexp, "lastIndex", 𝔽(nextIndex), true)를 수행한다.
  13. accumulatedResult를 빈 String이라고 하자.
  14. nextSourcePosition을 0이라고 하자.
  15. results의 각 요소 result에 대해, 다음을 수행한다.
    1. resultLength를 ? LengthOfArrayLike(result)라고 하자.
    2. nCapturesmax(resultLength - 1, 0)이라고 하자.
    3. matched를 ? ToString(? Get(result, "0"))라고 하자.
    4. matchLengthmatched의 길이라고 하자.
    5. position을 ? ToIntegerOrInfinity(? Get(result, "index"))라고 하자.
    6. position을 0과 lengthS 사이로 클램프한 결과로 설정한다.
    7. captures를 새로운 빈 List라고 하자.
    8. captureNumber를 1이라고 하자.
    9. captureNumbernCaptures인 동안 반복한다,
      1. capN을 ? Get(result, ! ToString(𝔽(captureNumber)))라고 하자.
      2. capNundefined가 아니면,
        1. capN을 ? ToString(capN)으로 설정한다.
      3. capNcaptures에 추가한다.
      4. NOTE: captureNumber = 1이면, 앞 단계는 첫 번째 요소를 captures 안에 넣는다(인덱스 0). 더 일반적으로, captureNumberth 캡처(captureNumberth 캡처 괄호 집합이 캡처한 문자들)는 captures[captureNumber - 1]에 있다.
      5. captureNumbercaptureNumber + 1로 설정한다.
    10. namedCaptures를 ? Get(result, "groups")라고 하자.
    11. functionalReplacetrue이면,
      1. replacerArgs를 « matched », captures, 및 « 𝔽(position), str »의 리스트 연결이라고 하자.
      2. namedCapturesundefined가 아니면,
        1. namedCapturesreplacerArgs에 추가한다.
      3. replacementValue를 ? Call(replaceValue, undefined, replacerArgs)라고 하자.
      4. replacementString을 ? ToString(replacementValue)라고 하자.
    12. 그렇지 않으면,
      1. namedCapturesundefined가 아니면,
        1. namedCaptures를 ? ToObject(namedCaptures)로 설정한다.
      2. replacementString을 ? GetSubstitution(matched, str, position, captures, namedCaptures, replaceValue)라고 하자.
    13. positionnextSourcePosition이면,
      1. NOTE: position은 보통 뒤로 이동해서는 안 된다. 만약 이동한다면, 이는 제대로 동작하지 않는 RegExp 서브클래스이거나 접근으로 촉발된 부수 효과를 사용해 regexp의 global 플래그 또는 다른 특성을 변경했음을 나타낸다. 이러한 경우, 대응하는 치환은 무시된다.
      2. accumulatedResultaccumulatedResult, strnextSourcePosition부터 position까지의 부분 문자열, 및 replacementString의 문자열 연결로 설정한다.
      3. nextSourcePositionposition + matchLength로 설정한다.
  16. nextSourcePositionlengthS이면, accumulatedResult를 반환한다.
  17. accumulatedResultstrnextSourcePosition부터의 부분 문자열의 문자열 연결을 반환한다.

이 메서드의 "name" 속성의 값은 "[Symbol.replace]"이다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. previousLastIndex를 ? Get(regexp, "lastIndex")라고 하자.
  5. previousLastIndex+0𝔽가 아니면,
    1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  6. result를 ? RegExpExec(regexp, str)라고 하자.
  7. currentLastIndex를 ? Get(regexp, "lastIndex")라고 하자.
  8. SameValue(currentLastIndex, previousLastIndex)가 false이면,
    1. Set(regexp, "lastIndex", previousLastIndex, true)를 수행한다.
  9. resultnull이면, -1𝔽을 반환한다.
  10. Get(result, "index")를 반환한다.

이 메서드의 "name" 속성의 값은 "[Symbol.search]"이다.

Note

검색을 수행할 때 이 RegExp 객체의 "lastIndex""global" 속성 값은 무시된다. "lastIndex" 속성은 변경되지 않은 채 남는다.

22.2.6.13 get RegExp.prototype.source

RegExp.prototype.source는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. regexp[[OriginalSource]] 내부 슬롯을 가지지 않으면,
    1. SameValue(regexp, %RegExp.prototype%)가 true이면, "(?:)"를 반환한다.
    2. TypeError 예외를 던진다.
  4. Assert: regexp[[OriginalFlags]] 내부 슬롯을 가진다.
  5. srcregexp.[[OriginalSource]]라고 하자.
  6. flagsregexp.[[OriginalFlags]]라고 하자.
  7. EscapeRegExpPattern(src, flags)를 반환한다.

22.2.6.13.1 EscapeRegExpPattern ( pattern, flags )

The abstract operation EscapeRegExpPattern takes arguments pattern (a String) and flags (a String) and returns a String. It performs the following steps when called:

  1. flags"v"를 포함하면,
    1. patternSymbolPattern[+UnicodeMode, +UnicodeSetsMode]라고 하자.
  2. 그렇지 않고 flags"u"를 포함하면,
    1. patternSymbolPattern[+UnicodeMode, ~UnicodeSetsMode]라고 하자.
  3. 그렇지 않으면,
    1. patternSymbolPattern[~UnicodeMode, ~UnicodeSetsMode]라고 하자.
  4. escapedPattern을 UTF-16으로 인코딩된 Unicode 코드 포인트(6.1.4)로 해석된 pattern과 동등한 patternSymbol의 형식을 가지며, 특정 코드 포인트가 아래 설명된 대로 escape된 String이라고 하자. escapedPatternpattern과 다를 수도 있고 다르지 않을 수도 있다; 그러나 escapedPatternpatternSymbol로 평가하여 생기는 Abstract Closure는 생성된 객체의 [[RegExpMatcher]] 내부 슬롯이 제공하는 Abstract Closure와 동일하게 동작해야 한다. 같은 patternflags 값으로 이 추상 연산을 여러 번 호출하면 동일한 결과를 생성해야 한다.
  5. 패턴 안에 나타나는 코드 포인트 / 또는 임의의 LineTerminator는, "/", escapedPattern, "/", 및 flags의 문자열 연결이 (적절한 어휘 문맥에서) 생성된 정규 표현식과 동일하게 동작하는 RegularExpressionLiteral로 파싱될 수 있도록 필요에 따라 escapedPattern에서 escape되어야 한다. 예를 들어, pattern"/"이면, escapedPattern은 그 밖의 가능성 중 "\/" 또는 "\u002F"일 수 있지만 "/"일 수는 없다. 왜냐하면 flags가 뒤따르는 ///RegularExpressionLiteral이 아니라 SingleLineComment로 파싱되기 때문이다. pattern이 빈 String이면, escapedPattern"(?:)"로 두어 이 명세를 만족할 수 있다.
  6. escapedPattern을 반환한다.
Note

이름이 비슷하지만, RegExp.escape와 EscapeRegExpPattern은 비슷한 동작을 수행하지 않는다. 전자는 패턴 안에서 표현하기 위해 문자열을 escape하는 반면, 이 함수는 문자열로 표현하기 위해 패턴을 escape한다.

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

Note 1

이 메서드는 string을 String으로 변환한 결과의 부분 문자열들이 저장된 Array를 반환한다. 부분 문자열들은 this 값 정규 표현식의 매치를 왼쪽에서 오른쪽으로 검색하여 결정된다; 이러한 출현들은 반환된 배열 안의 어떤 String의 일부도 아니지만, String 값을 나누는 역할을 한다.

this 값은 빈 정규 표현식이거나 빈 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", ""]

limitundefined가 아니면, 출력 배열은 limit개 이하의 요소를 포함하도록 잘린다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. speciesConstructor를 ? SpeciesConstructor(regexp, %RegExp%)라고 하자.
  5. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  6. flags"u"를 포함하거나 flags"v"를 포함하면, unicodeMatchingtrue라고 하자.
  7. 그렇지 않으면, unicodeMatchingfalse라고 하자.
  8. flags"y"를 포함하면, newFlagsflags라고 하자.
  9. 그렇지 않으면, newFlagsflags"y"의 문자열 연결이라고 하자.
  10. splitter를 ? Construct(speciesConstructor, « regexp, newFlags »)라고 하자.
  11. array를 ! ArrayCreate(0)이라고 하자.
  12. lengthA를 0이라고 하자.
  13. limitundefined이면 lim을 232 - 1이라고 하자; 그렇지 않으면 lim(? ToUint32(limit))라고 하자.
  14. lim = 0이면, array를 반환한다.
  15. str이 빈 String이면,
    1. matchResult를 ? RegExpExec(splitter, str)라고 하자.
    2. matchResultnull이 아니면, array를 반환한다.
    3. CreateDataPropertyOrThrow(array, "0", str)를 수행한다.
    4. array를 반환한다.
  16. sizestr의 길이라고 하자.
  17. lastMatchEnd를 0이라고 하자.
  18. searchIndexlastMatchEnd라고 하자.
  19. searchIndex < size인 동안 반복한다,
    1. Set(splitter, "lastIndex", 𝔽(searchIndex), true)를 수행한다.
    2. matchResult를 ? RegExpExec(splitter, str)라고 하자.
    3. matchResultnull이면,
      1. searchIndexAdvanceStringIndex(str, searchIndex, unicodeMatching)로 설정한다.
    4. 그렇지 않으면,
      1. matchEnd(? ToLength(? Get(splitter, "lastIndex")))라고 하자.
      2. matchEndmin(matchEnd, size)로 설정한다.
      3. matchEnd = lastMatchEnd이면,
        1. searchIndexAdvanceStringIndex(str, searchIndex, unicodeMatching)로 설정한다.
      4. 그렇지 않으면,
        1. substringstrlastMatchEnd부터 searchIndex까지의 부분 문자열이라고 하자.
        2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)를 수행한다.
        3. lengthAlengthA + 1로 설정한다.
        4. lengthA = lim이면, array를 반환한다.
        5. lastMatchEndmatchEnd로 설정한다.
        6. numberOfCaptures를 ? LengthOfArrayLike(matchResult)라고 하자.
        7. numberOfCapturesmax(numberOfCaptures - 1, 0)으로 설정한다.
        8. captureIndex를 1이라고 하자.
        9. captureIndexnumberOfCaptures인 동안 반복한다,
          1. nextCapture를 ? Get(matchResult, ! ToString(𝔽(captureIndex)))라고 하자.
          2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), nextCapture)를 수행한다.
          3. captureIndexcaptureIndex + 1로 설정한다.
          4. lengthAlengthA + 1로 설정한다.
          5. lengthA = lim이면, array를 반환한다.
        10. searchIndexlastMatchEnd로 설정한다.
  20. substringstrlastMatchEnd부터 size까지의 부분 문자열이라고 하자.
  21. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)를 수행한다.
  22. array를 반환한다.

이 메서드의 "name" 속성의 값은 "[Symbol.split]"이다.

Note 2

이 메서드는 이 RegExp 객체의 "global""sticky" 속성 값을 무시한다.

22.2.6.15 get RegExp.prototype.sticky

RegExp.prototype.sticky는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0079 (LATIN SMALL LETTER Y)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.16 RegExp.prototype.test ( str )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. string을 ? ToString(str)이라고 하자.
  4. match를 ? RegExpExec(regexp, string)이라고 하자.
  5. matchnull이면, false를 반환한다.
  6. true를 반환한다.

22.2.6.17 RegExp.prototype.toString ( )

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. pattern을 ? ToString(? Get(regexp, "source"))라고 하자.
  4. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  5. result"/", pattern, "/", 및 flags의 문자열 연결이라고 하자.
  6. result를 반환한다.
Note

반환된 String은 이 객체와 같은 동작을 가진 또 다른 RegExp 객체로 평가되는 RegularExpressionLiteral의 형식을 가진다.

22.2.6.18 get RegExp.prototype.unicode

RegExp.prototype.unicode는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0075 (LATIN SMALL LETTER U)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.19 get RegExp.prototype.unicodeSets

RegExp.prototype.unicodeSets는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0076 (LATIN SMALL LETTER V)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.7 RegExp 매칭을 위한 추상 연산

22.2.7.1 RegExpExec ( regexp, str )

The abstract operation RegExpExec takes arguments regexp (an Object) and str (a String) and returns either a normal completion containing either an Object or null, or a throw completion. It performs the following steps when called:

  1. exec를 ? Get(regexp, "exec")라고 하자.
  2. IsCallable(exec)가 true이면,
    1. result를 ? Call(exec, regexp, « str »)라고 하자.
    2. result가 Object가 아니고 resultnull도 아니면, TypeError 예외를 던진다.
    3. result를 반환한다.
  3. RequireInternalSlot(regexp, [[RegExpMatcher]])를 수행한다.
  4. RegExpBuiltinExec(regexp, str)를 반환한다.
Note

호출 가능한 "exec" 속성을 찾지 못하면 이 알고리즘은 내장 RegExp 매칭 알고리즘 사용을 시도하는 것으로 대체된다. 이는 정규 표현식을 사용하는 대부분의 내장 알고리즘이 "exec"의 동적 속성 조회를 수행하지 않았던 이전 판을 위해 작성된 코드와 호환되는 동작을 제공한다.

22.2.7.2 RegExpBuiltinExec ( regexp, str )

The abstract operation RegExpBuiltinExec takes arguments regexp (an initialized RegExp instance) and str (a String) and returns either a normal completion containing either an Array exotic object or null, or a throw completion. It performs the following steps when called:

  1. lengthstr의 길이라고 하자.
  2. lastIndex(? ToLength(! Get(regexp, "lastIndex")))라고 하자.
  3. flagsregexp.[[OriginalFlags]]라고 하자.
  4. flags"g"를 포함하면 globaltrue라고 하자; 그렇지 않으면 globalfalse라고 하자.
  5. flags"y"를 포함하면 stickytrue라고 하자; 그렇지 않으면 stickyfalse라고 하자.
  6. flags"d"를 포함하면 hasIndicestrue라고 하자; 그렇지 않으면 hasIndicesfalse라고 하자.
  7. globalfalse이고 stickyfalse이면, lastIndex를 0으로 설정한다.
  8. matcherregexp.[[RegExpMatcher]]라고 하자.
  9. flags"u"를 포함하거나 flags"v"를 포함하면 fullUnicodetrue라고 하자; 그렇지 않으면 fullUnicodefalse라고 하자.
  10. matchSucceededfalse라고 하자.
  11. fullUnicodetrue이면 inputStringToCodePoints(str)라고 하자; 그렇지 않으면 inputstr의 요소인 코드 단위들을 요소로 가지는 List라고 하자.
  12. NOTE: input의 각 요소는 character로 간주된다.
  13. matchSucceededfalse인 동안 반복한다,
    1. lastIndex > length이면,
      1. globaltrue이거나 stickytrue이면,
        1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
      2. null을 반환한다.
    2. inputIndexstr의 요소 lastIndex에서 얻은 character의 input 안의 인덱스라고 하자.
    3. rmatcher(input, inputIndex)라고 하자.
    4. rfailure이면,
      1. stickytrue이면,
        1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
        2. null을 반환한다.
      2. lastIndexAdvanceStringIndex(str, lastIndex, fullUnicode)로 설정한다.
    5. 그렇지 않으면,
      1. Assert: rMatchState이다.
      2. matchSucceededtrue로 설정한다.
  14. endIndexr.[[EndIndex]]라고 하자.
  15. fullUnicodetrue이면, endIndexGetStringIndex(str, endIndex)로 설정한다.
  16. globaltrue이거나 stickytrue이면,
    1. Set(regexp, "lastIndex", 𝔽(endIndex), true)를 수행한다.
  17. nr.[[Captures]] 안의 요소 개수라고 하자.
  18. Assert: n = regexp.[[RegExpRecord]].[[CapturingGroupsCount]].
  19. Assert: n < 232 - 1.
  20. array를 ! ArrayCreate(n + 1)이라고 하자.
  21. Assert: array"length" 속성의 수학적 값n + 1이다.
  22. CreateDataPropertyOrThrow(array, "index", 𝔽(lastIndex))를 수행한다.
  23. CreateDataPropertyOrThrow(array, "input", str)를 수행한다.
  24. matchMatch Record { [[StartIndex]]: lastIndex, [[EndIndex]]: endIndex }라고 하자.
  25. indices를 새로운 빈 List라고 하자.
  26. groupNames를 새로운 빈 List라고 하자.
  27. matchindices에 추가한다.
  28. matchedSubstrGetMatchString(str, match)라고 하자.
  29. CreateDataPropertyOrThrow(array, "0", matchedSubstr)를 수행한다.
  30. regexp가 어떤 GroupName이든 포함하면,
    1. groupsOrdinaryObjectCreate(null)라고 하자.
    2. hasGroupstrue라고 하자.
  31. 그렇지 않으면,
    1. groupsundefined라고 하자.
    2. hasGroupsfalse라고 하자.
  32. CreateDataPropertyOrThrow(array, "groups", groups)를 수행한다.
  33. matchedGroupNames를 새로운 빈 List라고 하자.
  34. 1 ≤ in을 만족하는 각 정수 i에 대해, 오름차순으로, 다음을 수행한다.
    1. captureIr.[[Captures]]ith 요소라고 하자.
    2. captureIundefined이면,
      1. capturedValueundefined라고 하자.
      2. undefinedindices에 추가한다.
    3. 그렇지 않으면,
      1. captureStartcaptureI.[[StartIndex]]라고 하자.
      2. captureEndcaptureI.[[EndIndex]]라고 하자.
      3. fullUnicodetrue이면,
        1. captureStartGetStringIndex(str, captureStart)로 설정한다.
        2. captureEndGetStringIndex(str, captureEnd)로 설정한다.
      4. captureMatch Record { [[StartIndex]]: captureStart, [[EndIndex]]: captureEnd }라고 하자.
      5. capturedValueGetMatchString(str, capture)라고 하자.
      6. captureindices에 추가한다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), capturedValue)를 수행한다.
    5. regexpith capture가 GroupName으로 정의되었으면,
      1. s를 그 GroupNameCapturingGroupName이라고 하자.
      2. matchedGroupNamess를 포함하면,
        1. Assert: capturedValueundefined이다.
        2. undefinedgroupNames에 추가한다.
      3. 그렇지 않으면,
        1. capturedValueundefined가 아니면 smatchedGroupNames에 추가한다.
        2. NOTE: s라는 이름의 그룹이 여러 개 있으면, 이 시점에서 groups는 이미 s 속성을 가질 수 있다. 그러나 groups는 모든 속성이 쓰기 가능한 데이터 속성인 보통 객체이므로, CreateDataPropertyOrThrow 호출은 그럼에도 성공하는 것이 보장된다.
        3. CreateDataPropertyOrThrow(groups, s, capturedValue)를 수행한다.
        4. sgroupNames에 추가한다.
    6. 그렇지 않으면,
      1. undefinedgroupNames에 추가한다.
  35. hasIndicestrue이면,
    1. indicesArrayMakeMatchIndicesIndexPairArray(str, indices, groupNames, hasGroups)라고 하자.
    2. CreateDataPropertyOrThrow(array, "indices", indicesArray)를 수행한다.
  36. array를 반환한다.

22.2.7.3 AdvanceStringIndex ( str, index, unicode )

The abstract operation AdvanceStringIndex takes arguments str (a String), index (a non-negative integer), and unicode (a Boolean) and returns a non-negative integer. It performs the following steps when called:

  1. Assert: index ≤ 253 - 1.
  2. unicodefalse이면, index + 1을 반환한다.
  3. lengthstr의 길이라고 하자.
  4. index + 1 ≥ length이면, index + 1을 반환한다.
  5. cpCodePointAt(str, index)라고 하자.
  6. index + cp.[[CodeUnitCount]]를 반환한다.

22.2.7.4 GetStringIndex ( str, codePointIndex )

The abstract operation GetStringIndex takes arguments str (a String) and codePointIndex (a non-negative integer) and returns a non-negative integer. 이 연산은 6.1.4에 설명된 대로 str을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석하고, 그러한 인덱스가 존재할 때 코드 포인트 인덱스 codePointIndex에 대응하는 코드 단위 인덱스를 반환한다. 그렇지 않으면 str의 길이를 반환한다. It performs the following steps when called:

  1. str이 빈 String이면 0을 반환한다.
  2. lenstr의 길이라고 하자.
  3. codeUnitCount를 0이라고 하자.
  4. codePointCount를 0이라고 하자.
  5. codeUnitCount < len인 동안 반복한다,
    1. codePointCount = codePointIndex이면 codeUnitCount를 반환한다.
    2. cpCodePointAt(str, codeUnitCount)라고 하자.
    3. codeUnitCountcodeUnitCount + cp.[[CodeUnitCount]]로 설정한다.
    4. codePointCountcodePointCount + 1로 설정한다.
  6. len을 반환한다.

22.2.7.5 Match Records

Match Record는 정규 표현식 매치 또는 캡처의 시작 및 끝 인덱스를 캡슐화하는 데 사용되는 Record 값이다.

Match Record는 Table 67에 나열된 필드를 가진다.

Table 67: Match Record 필드
필드 이름 의미
[[StartIndex]] 음이 아닌 정수 매치가 시작되는(포함) 지점까지 문자열의 시작부터 센 코드 단위의 수.
[[EndIndex]] 정수[[StartIndex]] 매치가 끝나는(제외) 지점까지 문자열의 시작부터 센 코드 단위의 수.

22.2.7.6 GetMatchString ( str, match )

The abstract operation GetMatchString takes arguments str (a String) and match (a Match Record) and returns a String. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]str의 길이.
  2. strmatch.[[StartIndex]]부터 match.[[EndIndex]]까지의 부분 문자열을 반환한다.

22.2.7.7 GetMatchIndexPair ( str, match )

The abstract operation GetMatchIndexPair takes arguments str (a String) and match (a Match Record) and returns an Array. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]str의 길이.
  2. CreateArrayFromList𝔽(match.[[StartIndex]]), 𝔽(match.[[EndIndex]]) »)를 반환한다.

22.2.7.8 MakeMatchIndicesIndexPairArray ( str, indices, groupNames, hasGroups )

The abstract operation MakeMatchIndicesIndexPairArray takes arguments str (a String), indices (a List of either Match Records or undefined), groupNames (a List of either Strings or undefined), and hasGroups (a Boolean) and returns an Array. It performs the following steps when called:

  1. nindices 안의 요소 개수라고 하자.
  2. Assert: n < 232 - 1.
  3. Assert: groupNamesn - 1개의 요소를 가진다.
  4. NOTE: groupNames Listindices[1]부터 시작하여 indices List와 정렬된 요소들을 포함한다.
  5. array를 ! ArrayCreate(n)이라고 하자.
  6. hasGroupstrue이면,
    1. groupsOrdinaryObjectCreate(null)라고 하자.
  7. 그렇지 않으면,
    1. groupsundefined라고 하자.
  8. CreateDataPropertyOrThrow(array, "groups", groups)를 수행한다.
  9. 0 ≤ i < n을 만족하는 각 정수 i에 대해, 오름차순으로, 다음을 수행한다.
    1. matchIndicesindices[i]라고 하자.
    2. matchIndicesundefined가 아니면,
      1. matchIndexPairGetMatchIndexPair(str, matchIndices)라고 하자.
    3. 그렇지 않으면,
      1. matchIndexPairundefined라고 하자.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), matchIndexPair)를 수행한다.
    5. i > 0이면,
      1. namegroupNames[i - 1]이라고 하자.
      2. nameundefined가 아니면,
        1. Assert: groupsundefined가 아니다.
        2. NOTE: 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 표현이다.

Note

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 Iterator 객체

RegExp String Iterator는 어떤 특정 String 인스턴스 객체에 대한 특정 반복을, 어떤 특정 RegExp 인스턴스 객체에 대해 매치하면서 나타내는 객체이다. RegExp String Iterator 객체에는 이름 있는 생성자가 없다. 대신, RegExp String Iterator 객체는 RegExp 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

22.2.9.1 CreateRegExpStringIterator ( regexp, str, global, fullUnicode )

The abstract operation CreateRegExpStringIterator takes arguments regexp (an Object), str (a String), global (a Boolean), and fullUnicode (a Boolean) and returns an Object. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%RegExpStringIteratorPrototype%, « [[IteratingRegExp]], [[IteratedString]], [[Global]], [[Unicode]], [[Done]] »)라고 하자.
  2. iterator.[[IteratingRegExp]]regexp로 설정한다.
  3. iterator.[[IteratedString]]str로 설정한다.
  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. iteratorObjthis 값이라고 하자.
  2. iteratorObj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratorObjRegExp String Iterator Object Instance의 모든 내부 슬롯(22.2.9.3를 보라)을 가지지 않으면, TypeError 예외를 던진다.
  4. iteratorObj.[[Done]]true이면,
    1. CreateIteratorResultObject(undefined, true)를 반환한다.
  5. regexpiteratorObj.[[IteratingRegExp]]라고 하자.
  6. striteratorObj.[[IteratedString]]이라고 하자.
  7. globaliteratorObj.[[Global]]이라고 하자.
  8. fullUnicodeiteratorObj.[[Unicode]]라고 하자.
  9. match를 ? RegExpExec(regexp, str)라고 하자.
  10. matchnull이면,
    1. iteratorObj.[[Done]]true로 설정한다.
    2. CreateIteratorResultObject(undefined, true)를 반환한다.
  11. globalfalse이면,
    1. iteratorObj.[[Done]]true로 설정한다.
    2. CreateIteratorResultObject(match, false)를 반환한다.
  12. matchStr을 ? ToString(? Get(match, "0"))라고 하자.
  13. matchStr이 빈 String이면,
    1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))라고 하자.
    2. nextIndexAdvanceStringIndex(str, 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 인스턴스는 처음에 Table 68에 나열된 내부 슬롯을 가지고 생성된다.

Table 68: RegExp String Iterator 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[IteratingRegExp]] Object 반복에 사용되는 정규 표현식. IsRegExp([[IteratingRegExp]])는 처음에 true이다.
[[IteratedString]] String 반복 대상인 String 값.
[[Global]] Boolean [[IteratingRegExp]]가 전역인지 아닌지를 나타낸다.
[[Unicode]] Boolean [[IteratingRegExp]]가 Unicode 모드인지 아닌지를 나타낸다.
[[Done]] Boolean 반복이 완료되었는지 아닌지를 나타낸다.