ECMAScript® 2024 Language Specification

Draft ECMA-262 / February 15, 2024

22.1 String Objects

22.1.1 The String Constructor

The String constructor:

  • is %String%.
  • is the initial value of the "String" property of the global object.
  • creates and initializes a new String object when called as a constructor.
  • performs a type conversion when called as a function rather than as a constructor.
  • may be used as the value of an extends clause of a class definition. Subclass constructors that intend to inherit the specified String behaviour must include a super call to the String constructor to create and initialize the subclass instance with a [[StringData]] internal slot.

22.1.1.1 String ( value )

This function performs the following steps when called:

  1. If value is not present, then
    1. Let s be the empty String.
  2. Else,
    1. If NewTarget is undefined and value is a Symbol, return SymbolDescriptiveString(value).
    2. Let s be ? ToString(value).
  3. If NewTarget is undefined, return s.
  4. Return StringCreate(s, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%")).

22.1.2 Properties of the String Constructor

The String constructor:

  • has a [[Prototype]] internal slot whose value is %Function.prototype%.
  • has the following properties:

22.1.2.1 String.fromCharCode ( ...codeUnits )

This function may be called with any number of arguments which form the rest parameter codeUnits.

It performs the following steps when called:

  1. Let result be the empty String.
  2. For each element next of codeUnits, do
    1. Let nextCU be the code unit whose numeric value is (? ToUint16(next)).
    2. Set result to the string-concatenation of result and nextCU.
  3. Return result.

The "length" property of this function is 1𝔽.

22.1.2.2 String.fromCodePoint ( ...codePoints )

This function may be called with any number of arguments which form the rest parameter codePoints.

It performs the following steps when called:

  1. Let result be the empty String.
  2. For each element next of codePoints, do
    1. Let nextCP be ? ToNumber(next).
    2. If IsIntegralNumber(nextCP) is false, throw a RangeError exception.
    3. If (nextCP) < 0 or (nextCP) > 0x10FFFF, throw a RangeError exception.
    4. Set result to the string-concatenation of result and UTF16EncodeCodePoint((nextCP)).
  3. Assert: If codePoints is empty, then result is the empty String.
  4. Return result.

The "length" property of this function is 1𝔽.

22.1.2.3 String.prototype

The initial value of String.prototype is the String prototype object.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

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

This function may be called with a variable number of arguments. The first argument is template and the remainder of the arguments form the List substitutions.

It performs the following steps when called:

  1. Let substitutionCount be the number of elements in substitutions.
  2. Let cooked be ? ToObject(template).
  3. Let literals be ? ToObject(? Get(cooked, "raw")).
  4. Let literalCount be ? LengthOfArrayLike(literals).
  5. If literalCount ≤ 0, return the empty String.
  6. Let R be the empty String.
  7. Let nextIndex be 0.
  8. Repeat,
    1. Let nextLiteralVal be ? Get(literals, ! ToString(𝔽(nextIndex))).
    2. Let nextLiteral be ? ToString(nextLiteralVal).
    3. Set R to the string-concatenation of R and nextLiteral.
    4. If nextIndex + 1 = literalCount, return R.
    5. If nextIndex < substitutionCount, then
      1. Let nextSubVal be substitutions[nextIndex].
      2. Let nextSub be ? ToString(nextSubVal).
      3. Set R to the string-concatenation of R and nextSub.
    6. Set nextIndex to nextIndex + 1.
Note

This function is intended for use as a tag function of a Tagged Template (13.3.11). When called as such, the first argument will be a well formed template object and the rest parameter will contain the substitution values.

22.1.3 Properties of the String Prototype Object

The String prototype object:

  • is %String.prototype%.
  • is a String exotic object and has the internal methods specified for such objects.
  • has a [[StringData]] internal slot whose value is the empty String.
  • has a "length" property whose initial value is +0𝔽 and whose attributes are { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
  • has a [[Prototype]] internal slot whose value is %Object.prototype%.

Unless explicitly stated otherwise, the methods of the String prototype object defined below are not generic and the this value passed to them must be either a String value or an object that has a [[StringData]] internal slot that has been initialized to a String value.

22.1.3.1 String.prototype.at ( index )

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let len be the length of S.
  4. Let relativeIndex be ? ToIntegerOrInfinity(index).
  5. If relativeIndex ≥ 0, then
    1. Let k be relativeIndex.
  6. Else,
    1. Let k be len + relativeIndex.
  7. If k < 0 or klen, return undefined.
  8. Return the substring of S from k to k + 1.

22.1.3.2 String.prototype.charAt ( pos )

Note 1

This method returns a single element String containing the code unit at index pos within the String value resulting from converting this object to a String. If there is no element at that index, the result is the empty String. The result is a String value, not a String object.

If pos is an integral Number, then the result of x.charAt(pos) is equivalent to the result of x.substring(pos, pos + 1).

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let position be ? ToIntegerOrInfinity(pos).
  4. Let size be the length of S.
  5. If position < 0 or positionsize, return the empty String.
  6. Return the substring of S from position to position + 1.
Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.3 String.prototype.charCodeAt ( pos )

Note 1

This method returns a Number (a non-negative integral Number less than 216) that is the numeric value of the code unit at index pos within the String resulting from converting this object to a String. If there is no element at that index, the result is NaN.

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let position be ? ToIntegerOrInfinity(pos).
  4. Let size be the length of S.
  5. If position < 0 or positionsize, return NaN.
  6. Return the Number value for the numeric value of the code unit at index position within the String S.
Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore it can be transferred to other kinds of objects for use as a method.

22.1.3.4 String.prototype.codePointAt ( pos )

Note 1

This method returns a non-negative integral Number less than or equal to 0x10FFFF𝔽 that is the numeric value of the UTF-16 encoded code point (6.1.4) starting at the string element at index pos within the String resulting from converting this object to a String. If there is no element at that index, the result is undefined. If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let position be ? ToIntegerOrInfinity(pos).
  4. Let size be the length of S.
  5. If position < 0 or positionsize, return undefined.
  6. Let cp be CodePointAt(S, position).
  7. Return 𝔽(cp.[[CodePoint]]).
Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore it can be transferred to other kinds of objects for use as a method.

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

Note 1

When this method is called it returns the String value consisting of the code units of the this value (converted to a String) followed by the code units of each of the arguments converted to a String. The result is a String value, not a String object.

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let R be S.
  4. For each element next of args, do
    1. Let nextString be ? ToString(next).
    2. Set R to the string-concatenation of R and nextString.
  5. Return R.

The "length" property of this method is 1𝔽.

Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore it can be transferred to other kinds of objects for use as a method.

22.1.3.6 String.prototype.constructor

The initial value of String.prototype.constructor is %String%.

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

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let isRegExp be ? IsRegExp(searchString).
  4. If isRegExp is true, throw a TypeError exception.
  5. Let searchStr be ? ToString(searchString).
  6. Let len be the length of S.
  7. If endPosition is undefined, let pos be len; else let pos be ? ToIntegerOrInfinity(endPosition).
  8. Let end be the result of clamping pos between 0 and len.
  9. Let searchLength be the length of searchStr.
  10. If searchLength = 0, return true.
  11. Let start be end - searchLength.
  12. If start < 0, return false.
  13. Let substring be the substring of S from start to end.
  14. If substring is searchStr, return true.
  15. Return false.
Note 1

This method returns true if the sequence of code units of searchString converted to a String is the same as the corresponding code units of this object (converted to a String) starting at endPosition - length(this). Otherwise it returns false.

Note 2

Throwing an exception if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.

Note 3

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

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

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let isRegExp be ? IsRegExp(searchString).
  4. If isRegExp is true, throw a TypeError exception.
  5. Let searchStr be ? ToString(searchString).
  6. Let pos be ? ToIntegerOrInfinity(position).
  7. Assert: If position is undefined, then pos is 0.
  8. Let len be the length of S.
  9. Let start be the result of clamping pos between 0 and len.
  10. Let index be StringIndexOf(S, searchStr, start).
  11. If index ≠ -1, return true.
  12. Return false.
Note 1

If searchString appears as a substring of the result of converting this object to a String, at one or more indices that are greater than or equal to position, this function returns true; otherwise, it returns false. If position is undefined, 0 is assumed, so as to search all of the String.

Note 2

Throwing an exception if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.

Note 3

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

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

Note 1

If searchString appears as a substring of the result of converting this object to a String, at one or more indices that are greater than or equal to position, then the smallest such index is returned; otherwise, -1𝔽 is returned. If position is undefined, +0𝔽 is assumed, so as to search all of the String.

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let searchStr be ? ToString(searchString).
  4. Let pos be ? ToIntegerOrInfinity(position).
  5. Assert: If position is undefined, then pos is 0.
  6. Let len be the length of S.
  7. Let start be the result of clamping pos between 0 and len.
  8. Return 𝔽(StringIndexOf(S, searchStr, start)).
Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.10 String.prototype.isWellFormed ( )

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Return IsStringWellFormedUnicode(S).

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

Note 1

If searchString appears as a substring of the result of converting this object to a String at one or more indices that are smaller than or equal to position, then the greatest such index is returned; otherwise, -1𝔽 is returned. If position is undefined, the length of the String value is assumed, so as to search all of the String.

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let searchStr be ? ToString(searchString).
  4. Let numPos be ? ToNumber(position).
  5. Assert: If position is undefined, then numPos is NaN.
  6. If numPos is NaN, let pos be +∞; otherwise, let pos be ! ToIntegerOrInfinity(numPos).
  7. Let len be the length of S.
  8. Let searchLen be the length of searchStr.
  9. Let start be the result of clamping pos between 0 and len - searchLen.
  10. If searchStr is the empty String, return 𝔽(start).
  11. For each integer i such that 0 ≤ istart, in descending order, do
    1. Let candidate be the substring of S from i to i + searchLen.
    2. If candidate is searchStr, return 𝔽(i).
  12. Return -1𝔽.
Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

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

An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement this method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of this method is used:

This method returns a Number other than NaN representing the result of an implementation-defined locale-sensitive String comparison of the this value (converted to a String S) with that (converted to a String thatValue). The result is intended to correspond with a sort order of String values according to conventions of the host environment's current locale, and will be negative when S is ordered before thatValue, positive when S is ordered after thatValue, and zero in all other cases (representing no relative ordering between S and thatValue).

Before performing the comparisons, this method performs the following steps to prepare the Strings:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let thatValue be ? ToString(that).

The meaning of the optional second and third parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not assign any other interpretation to those parameter positions.

The actual return values are implementation-defined to permit encoding additional information in them, but this method, when considered as a method of two arguments, is required to be a consistent comparator defining a total ordering on the set of all Strings. This method is also required to recognize and honour canonical equivalence according to the Unicode Standard, including returning +0𝔽 when comparing distinguishable Strings that are canonically equivalent.

Note 1

This method itself is not directly suitable as an argument to Array.prototype.sort because the latter requires a function of two arguments.

Note 2

This method may rely on whatever language- and/or locale-sensitive comparison functionality is available to the ECMAScript environment from the host environment, and is intended to compare according to the conventions of the host environment's current locale. However, regardless of comparison capabilities, this method must recognize and honour canonical equivalence according to the Unicode Standard—for example, the following comparisons must all return +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")

For a definition and discussion of canonical equivalence see the Unicode Standard, chapters 2 and 3, as well as Unicode Standard Annex #15, Unicode Normalization Forms and Unicode Technical Note #5, Canonical Equivalence in Applications. Also see Unicode Technical Standard #10, Unicode Collation Algorithm.

It is recommended that this method should not honour Unicode compatibility equivalents or compatibility decompositions as defined in the Unicode Standard, chapter 3, section 3.7.

Note 3

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.13 String.prototype.match ( regexp )

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. If regexp is neither undefined nor null, then
    1. Let matcher be ? GetMethod(regexp, @@match).
    2. If matcher is not undefined, then
      1. Return ? Call(matcher, regexp, « O »).
  3. Let S be ? ToString(O).
  4. Let rx be ? RegExpCreate(regexp, undefined).
  5. Return ? Invoke(rx, @@match, « S »).
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.14 String.prototype.matchAll ( regexp )

This method performs a regular expression match of the String representing the this value against regexp and returns an iterator. Each iteration result's value is an Array containing the results of the match, or null if the String did not match.

It performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. If regexp is neither undefined nor null, then
    1. Let isRegExp be ? IsRegExp(regexp).
    2. If isRegExp is true, then
      1. Let flags be ? Get(regexp, "flags").
      2. Perform ? RequireObjectCoercible(flags).
      3. If ? ToString(flags) does not contain "g", throw a TypeError exception.
    3. Let matcher be ? GetMethod(regexp, @@matchAll).
    4. If matcher is not undefined, then
      1. Return ? Call(matcher, regexp, « O »).
  3. Let S be ? ToString(O).
  4. Let rx be ? RegExpCreate(regexp, "g").
  5. Return ? Invoke(rx, @@matchAll, « S »).
Note 1
This method is intentionally generic, it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.
Note 2
Similarly to String.prototype.split, String.prototype.matchAll is designed to typically act without mutating its inputs.

22.1.3.15 String.prototype.normalize ( [ form ] )

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. If form is undefined, let f be "NFC".
  4. Else, let f be ? ToString(form).
  5. If f is not one of "NFC", "NFD", "NFKC", or "NFKD", throw a RangeError exception.
  6. Let ns be the String value that is the result of normalizing S into the normalization form named by f as specified in the latest Unicode Standard, Normalization Forms.
  7. Return ns.
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore it can be transferred to other kinds of objects for use as a method.

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

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Return ? StringPaddingBuiltinsImpl(O, maxLength, fillString, end).

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

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Return ? StringPaddingBuiltinsImpl(O, maxLength, fillString, start).

22.1.3.17.1 StringPaddingBuiltinsImpl ( O, maxLength, fillString, placement )

The abstract operation StringPaddingBuiltinsImpl takes arguments O (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. Let S be ? ToString(O).
  2. Let intMaxLength be (? ToLength(maxLength)).
  3. Let stringLength be the length of S.
  4. If intMaxLengthstringLength, return S.
  5. If fillString is undefined, set fillString to the String value consisting solely of the code unit 0x0020 (SPACE).
  6. Else, set fillString to ? ToString(fillString).
  7. Return StringPad(S, intMaxLength, fillString, placement).

22.1.3.17.2 StringPad ( S, maxLength, fillString, placement )

The abstract operation StringPad takes arguments S (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. Let stringLength be the length of S.
  2. If maxLengthstringLength, return S.
  3. If fillString is the empty String, return S.
  4. Let fillLen be maxLength - stringLength.
  5. Let truncatedStringFiller be the String value consisting of repeated concatenations of fillString truncated to length fillLen.
  6. If placement is start, return the string-concatenation of truncatedStringFiller and S.
  7. Else, return the string-concatenation of S and truncatedStringFiller.
Note 1

The argument maxLength will be clamped such that it can be no smaller than the length of S.

Note 2

The argument fillString defaults to " " (the String value consisting of the code unit 0x0020 SPACE).

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. Let S be the String representation of n, formatted as a decimal number.
  2. Return StringPad(S, minLength, "0", start).

22.1.3.18 String.prototype.repeat ( count )

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let n be ? ToIntegerOrInfinity(count).
  4. If n < 0 or n = +∞, throw a RangeError exception.
  5. If n = 0, return the empty String.
  6. Return the String value that is made from n copies of S appended together.
Note 1

This method creates the String value consisting of the code units of the this value (converted to String) repeated count times.

Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.19 String.prototype.replace ( searchValue, replaceValue )

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. If searchValue is neither undefined nor null, then
    1. Let replacer be ? GetMethod(searchValue, @@replace).
    2. If replacer is not undefined, then
      1. Return ? Call(replacer, searchValue, « O, replaceValue »).
  3. Let string be ? ToString(O).
  4. Let searchString be ? ToString(searchValue).
  5. Let functionalReplace be IsCallable(replaceValue).
  6. If functionalReplace is false, then
    1. Set replaceValue to ? ToString(replaceValue).
  7. Let searchLength be the length of searchString.
  8. Let position be StringIndexOf(string, searchString, 0).
  9. If position = -1, return string.
  10. Let preceding be the substring of string from 0 to position.
  11. Let following be the substring of string from position + searchLength.
  12. If functionalReplace is true, then
    1. Let replacement be ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(position), string »)).
  13. Else,
    1. Assert: replaceValue is a String.
    2. Let captures be a new empty List.
    3. Let replacement be ! GetSubstitution(searchString, string, position, captures, undefined, replaceValue).
  14. Return the string-concatenation of preceding, replacement, and following.
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

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. For the purposes of this abstract operation, a decimal digit is a code unit in the inclusive interval from 0x0030 (DIGIT ZERO) to 0x0039 (DIGIT NINE). It performs the following steps when called:

  1. Let stringLength be the length of str.
  2. Assert: positionstringLength.
  3. Let result be the empty String.
  4. Let templateRemainder be replacementTemplate.
  5. Repeat, while templateRemainder is not the empty String,
    1. NOTE: The following steps isolate ref (a prefix of templateRemainder), determine refReplacement (its replacement), and then append that replacement to result.
    2. If templateRemainder starts with "$$", then
      1. Let ref be "$$".
      2. Let refReplacement be "$".
    3. Else if templateRemainder starts with "$`", then
      1. Let ref be "$`".
      2. Let refReplacement be the substring of str from 0 to position.
    4. Else if templateRemainder starts with "$&", then
      1. Let ref be "$&".
      2. Let refReplacement be matched.
    5. Else if templateRemainder starts with "$'" (0x0024 (DOLLAR SIGN) followed by 0x0027 (APOSTROPHE)), then
      1. Let ref be "$'".
      2. Let matchLength be the length of matched.
      3. Let tailPos be position + matchLength.
      4. Let refReplacement be the substring of str from min(tailPos, stringLength).
      5. NOTE: tailPos can exceed stringLength only if this abstract operation was invoked by a call to the intrinsic @@replace method of %RegExp.prototype% on an object whose "exec" property is not the intrinsic %RegExp.prototype.exec%.
    6. Else if templateRemainder starts with "$" followed by 1 or more decimal digits, then
      1. If templateRemainder starts with "$" followed by 2 or more decimal digits, let digitCount be 2. Otherwise, let digitCount be 1.
      2. Let digits be the substring of templateRemainder from 1 to 1 + digitCount.
      3. Let index be (StringToNumber(digits)).
      4. Assert: 0 ≤ index ≤ 99.
      5. Let captureLen be the number of elements in captures.
      6. If index > captureLen and digitCount = 2, then
        1. NOTE: When a two-digit replacement pattern specifies an index exceeding the count of capturing groups, it is treated as a one-digit replacement pattern followed by a literal digit.
        2. Set digitCount to 1.
        3. Set digits to the substring of digits from 0 to 1.
        4. Set index to (StringToNumber(digits)).
      7. Let ref be the substring of templateRemainder from 0 to 1 + digitCount.
      8. If 1 ≤ indexcaptureLen, then
        1. Let capture be captures[index - 1].
        2. If capture is undefined, then
          1. Let refReplacement be the empty String.
        3. Else,
          1. Let refReplacement be capture.
      9. Else,
        1. Let refReplacement be ref.
    7. Else if templateRemainder starts with "$<", then
      1. Let gtPos be StringIndexOf(templateRemainder, ">", 0).
      2. If gtPos = -1 or namedCaptures is undefined, then
        1. Let ref be "$<".
        2. Let refReplacement be ref.
      3. Else,
        1. Let ref be the substring of templateRemainder from 0 to gtPos + 1.
        2. Let groupName be the substring of templateRemainder from 2 to gtPos.
        3. Assert: namedCaptures is an Object.
        4. Let capture be ? Get(namedCaptures, groupName).
        5. If capture is undefined, then
          1. Let refReplacement be the empty String.
        6. Else,
          1. Let refReplacement be ? ToString(capture).
    8. Else,
      1. Let ref be the substring of templateRemainder from 0 to 1.
      2. Let refReplacement be ref.
    9. Let refLength be the length of ref.
    10. Set templateRemainder to the substring of templateRemainder from refLength.
    11. Set result to the string-concatenation of result and refReplacement.
  6. Return result.

22.1.3.20 String.prototype.replaceAll ( searchValue, replaceValue )

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. If searchValue is neither undefined nor null, then
    1. Let isRegExp be ? IsRegExp(searchValue).
    2. If isRegExp is true, then
      1. Let flags be ? Get(searchValue, "flags").
      2. Perform ? RequireObjectCoercible(flags).
      3. If ? ToString(flags) does not contain "g", throw a TypeError exception.
    3. Let replacer be ? GetMethod(searchValue, @@replace).
    4. If replacer is not undefined, then
      1. Return ? Call(replacer, searchValue, « O, replaceValue »).
  3. Let string be ? ToString(O).
  4. Let searchString be ? ToString(searchValue).
  5. Let functionalReplace be IsCallable(replaceValue).
  6. If functionalReplace is false, then
    1. Set replaceValue to ? ToString(replaceValue).
  7. Let searchLength be the length of searchString.
  8. Let advanceBy be max(1, searchLength).
  9. Let matchPositions be a new empty List.
  10. Let position be StringIndexOf(string, searchString, 0).
  11. Repeat, while position ≠ -1,
    1. Append position to matchPositions.
    2. Set position to StringIndexOf(string, searchString, position + advanceBy).
  12. Let endOfLastMatch be 0.
  13. Let result be the empty String.
  14. For each element p of matchPositions, do
    1. Let preserved be the substring of string from endOfLastMatch to p.
    2. If functionalReplace is true, then
      1. Let replacement be ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(p), string »)).
    3. Else,
      1. Assert: replaceValue is a String.
      2. Let captures be a new empty List.
      3. Let replacement be ! GetSubstitution(searchString, string, p, captures, undefined, replaceValue).
    4. Set result to the string-concatenation of result, preserved, and replacement.
    5. Set endOfLastMatch to p + searchLength.
  15. If endOfLastMatch < the length of string, then
    1. Set result to the string-concatenation of result and the substring of string from endOfLastMatch.
  16. Return result.

22.1.3.21 String.prototype.search ( regexp )

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. If regexp is neither undefined nor null, then
    1. Let searcher be ? GetMethod(regexp, @@search).
    2. If searcher is not undefined, then
      1. Return ? Call(searcher, regexp, « O »).
  3. Let string be ? ToString(O).
  4. Let rx be ? RegExpCreate(regexp, undefined).
  5. Return ? Invoke(rx, @@search, « string »).
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.22 String.prototype.slice ( start, end )

This method returns a substring of the result of converting this object to a String, starting from index start and running to, but not including, index end (or through the end of the String if end is undefined). If start is negative, it is treated as sourceLength + start where sourceLength is the length of the String. If end is negative, it is treated as sourceLength + end where sourceLength is the length of the String. The result is a String value, not a String object.

It performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let len be the length of S.
  4. Let intStart be ? ToIntegerOrInfinity(start).
  5. If intStart = -∞, let from be 0.
  6. Else if intStart < 0, let from be max(len + intStart, 0).
  7. Else, let from be min(intStart, len).
  8. If end is undefined, let intEnd be len; else let intEnd be ? ToIntegerOrInfinity(end).
  9. If intEnd = -∞, let to be 0.
  10. Else if intEnd < 0, let to be max(len + intEnd, 0).
  11. Else, let to be min(intEnd, len).
  12. If fromto, return the empty String.
  13. Return the substring of S from from to to.
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore it can be transferred to other kinds of objects for use as a method.

22.1.3.23 String.prototype.split ( separator, limit )

This method returns an Array into which substrings of the result of converting this object to a String have been stored. The substrings are determined by searching from left to right for occurrences of separator; these occurrences are not part of any String in the returned array, but serve to divide up the String value. The value of separator may be a String of any length or it may be an object, such as a RegExp, that has a @@split method.

It performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. If separator is neither undefined nor null, then
    1. Let splitter be ? GetMethod(separator, @@split).
    2. If splitter is not undefined, then
      1. Return ? Call(splitter, separator, « O, limit »).
  3. Let S be ? ToString(O).
  4. If limit is undefined, let lim be 232 - 1; else let lim be (? ToUint32(limit)).
  5. Let R be ? ToString(separator).
  6. If lim = 0, then
    1. Return CreateArrayFromList(« »).
  7. If separator is undefined, then
    1. Return CreateArrayFromListS »).
  8. Let separatorLength be the length of R.
  9. If separatorLength = 0, then
    1. Let head be the substring of S from 0 to lim.
    2. Let codeUnits be a List consisting of the sequence of code units that are the elements of head.
    3. Return CreateArrayFromList(codeUnits).
  10. If S is the empty String, return CreateArrayFromListS »).
  11. Let substrings be a new empty List.
  12. Let i be 0.
  13. Let j be StringIndexOf(S, R, 0).
  14. Repeat, while j ≠ -1,
    1. Let T be the substring of S from i to j.
    2. Append T to substrings.
    3. If the number of elements in substrings is lim, return CreateArrayFromList(substrings).
    4. Set i to j + separatorLength.
    5. Set j to StringIndexOf(S, R, i).
  15. Let T be the substring of S from i.
  16. Append T to substrings.
  17. Return CreateArrayFromList(substrings).
Note 1

The value of separator may be an empty String. In this case, separator does not match the empty substring at the beginning or end of the input String, nor does it match the empty substring at the end of the previous separator match. If separator is the empty String, the String is split up into individual code unit elements; the length of the result array equals the length of the String, and each substring contains one code unit.

If the this value is (or converts to) the empty String, the result depends on whether separator can match the empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, which is the empty String.

If separator is undefined, then the result array contains just one String, which is the this value (converted to a String). If limit is not undefined, then the output array is truncated so that it contains no more than limit elements.

Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

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

This method performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let isRegExp be ? IsRegExp(searchString).
  4. If isRegExp is true, throw a TypeError exception.
  5. Let searchStr be ? ToString(searchString).
  6. Let len be the length of S.
  7. If position is undefined, let pos be 0; else let pos be ? ToIntegerOrInfinity(position).
  8. Let start be the result of clamping pos between 0 and len.
  9. Let searchLength be the length of searchStr.
  10. If searchLength = 0, return true.
  11. Let end be start + searchLength.
  12. If end > len, return false.
  13. Let substring be the substring of S from start to end.
  14. If substring is searchStr, return true.
  15. Return false.
Note 1

This method returns true if the sequence of code units of searchString converted to a String is the same as the corresponding code units of this object (converted to a String) starting at index position. Otherwise it returns false.

Note 2

Throwing an exception if the first argument is a RegExp is specified in order to allow future editions to define extensions that allow such argument values.

Note 3

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.25 String.prototype.substring ( start, end )

This method returns a substring of the result of converting this object to a String, starting from index start and running to, but not including, index end of the String (or through the end of the String if end is undefined). The result is a String value, not a String object.

If either argument is NaN or negative, it is replaced with zero; if either argument is strictly greater than the length of the String, it is replaced with the length of the String.

If start is strictly greater than end, they are swapped.

It performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let len be the length of S.
  4. Let intStart be ? ToIntegerOrInfinity(start).
  5. If end is undefined, let intEnd be len; else let intEnd be ? ToIntegerOrInfinity(end).
  6. Let finalStart be the result of clamping intStart between 0 and len.
  7. Let finalEnd be the result of clamping intEnd between 0 and len.
  8. Let from be min(finalStart, finalEnd).
  9. Let to be max(finalStart, finalEnd).
  10. Return the substring of S from from to to.
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

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

An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement this method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of this method is used:

This method interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4.

It works exactly the same as toLowerCase except that it is intended to yield a locale-sensitive result corresponding with conventions of the host environment's current locale. There will only be a difference in the few cases (such as Turkish) where the rules for that language conflict with the regular Unicode case mappings.

The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.

Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

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

An ECMAScript implementation that includes the ECMA-402 Internationalization API must implement this method as specified in the ECMA-402 specification. If an ECMAScript implementation does not include the ECMA-402 API the following specification of this method is used:

This method interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4.

It works exactly the same as toUpperCase except that it is intended to yield a locale-sensitive result corresponding with conventions of the host environment's current locale. There will only be a difference in the few cases (such as Turkish) where the rules for that language conflict with the regular Unicode case mappings.

The meaning of the optional parameters to this method are defined in the ECMA-402 specification; implementations that do not include ECMA-402 support must not use those parameter positions for anything else.

Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.28 String.prototype.toLowerCase ( )

This method interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4.

It performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let sText be StringToCodePoints(S).
  4. Let lowerText be the result of toLowercase(sText), according to the Unicode Default Case Conversion algorithm.
  5. Let L be CodePointsToString(lowerText).
  6. Return L.

The result must be derived according to the locale-insensitive case mappings in the Unicode Character Database (this explicitly includes not only the file UnicodeData.txt, but also all locale-insensitive mappings in the file SpecialCasing.txt that accompanies it).

Note 1

The case mapping of some code points may produce multiple code points. In this case the result String may not be the same length as the source String. Because both toUpperCase and toLowerCase have context-sensitive behaviour, the methods are not symmetrical. In other words, s.toUpperCase().toLowerCase() is not necessarily equal to s.toLowerCase().

Note 2

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.29 String.prototype.toString ( )

This method performs the following steps when called:

  1. Return ? ThisStringValue(this value).
Note

For a String object, this method happens to return the same thing as the valueOf method.

22.1.3.30 String.prototype.toUpperCase ( )

This method interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4.

It behaves in exactly the same way as String.prototype.toLowerCase, except that the String is mapped using the toUppercase algorithm of the Unicode Default Case Conversion.

Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.31 String.prototype.toWellFormed ( )

This method returns a String representation of this object with all leading surrogates and trailing surrogates that are not part of a surrogate pair replaced with U+FFFD (REPLACEMENT CHARACTER).

It performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let strLen be the length of S.
  4. Let k be 0.
  5. Let result be the empty String.
  6. Repeat, while k < strLen,
    1. Let cp be CodePointAt(S, k).
    2. If cp.[[IsUnpairedSurrogate]] is true, then
      1. Set result to the string-concatenation of result and 0xFFFD (REPLACEMENT CHARACTER).
    3. Else,
      1. Set result to the string-concatenation of result and UTF16EncodeCodePoint(cp.[[CodePoint]]).
    4. Set k to k + cp.[[CodeUnitCount]].
  7. Return result.

22.1.3.32 String.prototype.trim ( )

This method interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4.

It performs the following steps when called:

  1. Let S be the this value.
  2. Return ? TrimString(S, start+end).
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

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. It interprets string as a sequence of UTF-16 encoded code points, as described in 6.1.4. It performs the following steps when called:

  1. Let str be ? RequireObjectCoercible(string).
  2. Let S be ? ToString(str).
  3. If where is start, then
    1. Let T be the String value that is a copy of S with leading white space removed.
  4. Else if where is end, then
    1. Let T be the String value that is a copy of S with trailing white space removed.
  5. Else,
    1. Assert: where is start+end.
    2. Let T be the String value that is a copy of S with both leading and trailing white space removed.
  6. Return T.

The definition of white space is the union of WhiteSpace and LineTerminator. When determining whether a Unicode code point is in Unicode general category “Space_Separator” (“Zs”), code unit sequences are interpreted as UTF-16 encoded code point sequences as specified in 6.1.4.

22.1.3.33 String.prototype.trimEnd ( )

This method interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4.

It performs the following steps when called:

  1. Let S be the this value.
  2. Return ? TrimString(S, end).
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.34 String.prototype.trimStart ( )

This method interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4.

It performs the following steps when called:

  1. Let S be the this value.
  2. Return ? TrimString(S, start).
Note

This method is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.

22.1.3.35 String.prototype.valueOf ( )

This method performs the following steps when called:

  1. Return ? 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. If value is a String, return value.
  2. If value is an Object and value has a [[StringData]] internal slot, then
    1. Let s be value.[[StringData]].
    2. Assert: s is a String.
    3. Return s.
  3. Throw a TypeError exception.

22.1.3.36 String.prototype [ @@iterator ] ( )

This method returns an Iterator object (27.1.1.2) that iterates over the code points of a String value, returning each code point as a String value.

It performs the following steps when called:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let s be ? ToString(O).
  3. Let closure be a new Abstract Closure with no parameters that captures s and performs the following steps when called:
    1. Let len be the length of s.
    2. Let position be 0.
    3. Repeat, while position < len,
      1. Let cp be CodePointAt(s, position).
      2. Let nextIndex be position + cp.[[CodeUnitCount]].
      3. Let resultString be the substring of s from position to nextIndex.
      4. Set position to nextIndex.
      5. Perform ? GeneratorYield(CreateIterResultObject(resultString, false)).
    4. Return undefined.
  4. Return CreateIteratorFromClosure(closure, "%StringIteratorPrototype%", %StringIteratorPrototype%).

The value of the "name" property of this method is "[Symbol.iterator]".

22.1.4 Properties of String Instances

String instances are String exotic objects and have the internal methods specified for such objects. String instances inherit properties from the String prototype object. String instances also have a [[StringData]] internal slot. The [[StringData]] internal slot is the String value represented by this String object.

String instances have a "length" property, and a set of enumerable properties with integer-indexed names.

22.1.4.1 length

The number of elements in the String value represented by this String object.

Once a String object is initialized, this property is unchanging. It has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

22.1.5 String Iterator Objects

A String Iterator is an object, that represents a specific iteration over some specific String instance object. There is not a named constructor for String Iterator objects. Instead, String iterator objects are created by calling certain methods of String instance objects.

22.1.5.1 The %StringIteratorPrototype% Object

The %StringIteratorPrototype% object:

  • has properties that are inherited by all String Iterator Objects.
  • is an ordinary object.
  • has a [[Prototype]] internal slot whose value is %IteratorPrototype%.
  • has the following properties:

22.1.5.1.1 %StringIteratorPrototype%.next ( )

  1. Return ? GeneratorResume(this value, empty, "%StringIteratorPrototype%").

22.1.5.1.2 %StringIteratorPrototype% [ @@toStringTag ]

The initial value of the @@toStringTag property is the String value "String Iterator".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.