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 )

When String is called with argument value, the following steps are taken:

  1. If value is not present, let s be the empty String.
  2. Else,
    1. If NewTarget is undefined and Type(value) is 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 )

The String.fromCharCode function may be called with any number of arguments which form the rest parameter codeUnits. The following steps are taken:

  1. Let length be the number of elements in codeUnits.
  2. Let elements be a new empty List.
  3. For each element next of codeUnits, do
    1. Let nextCU be (? ToUint16(next)).
    2. Append nextCU to the end of elements.
  4. Return the String value whose code units are the elements in the List elements. If codeUnits is empty, the empty String is returned.

The "length" property of the fromCharCode function is 1𝔽.

22.1.2.2 String.fromCodePoint ( ...codePoints )

The String.fromCodePoint function may be called with any number of arguments which form the rest parameter codePoints. The following steps are taken:

  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 the fromCodePoint 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 )

The String.raw 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. The following steps are taken:

  1. Let numberOfSubstitutions be the number of elements in substitutions.
  2. Let cooked be ? ToObject(template).
  3. Let raw be ? ToObject(? Get(cooked, "raw")).
  4. Let literalSegments be ? LengthOfArrayLike(raw).
  5. If literalSegments ≤ 0, return the empty String.
  6. Let stringElements be a new empty List.
  7. Let nextIndex be 0.
  8. Repeat,
    1. Let nextKey be ! ToString(𝔽(nextIndex)).
    2. Let nextSeg be ? ToString(? Get(raw, nextKey)).
    3. Append the code unit elements of nextSeg to the end of stringElements.
    4. If nextIndex + 1 = literalSegments, then
      1. Return the String value whose code units are the elements in the List stringElements. If stringElements has no elements, the empty String is returned.
    5. If nextIndex < numberOfSubstitutions, let next be substitutions[nextIndex].
    6. Else, let next be the empty String.
    7. Let nextSub be ? ToString(next).
    8. Append the code unit elements of nextSub to the end of stringElements.
    9. Set nextIndex to nextIndex + 1.
Note

The raw 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.

The abstract operation thisStringValue takes argument value. It performs the following steps when called:

  1. If Type(value) is String, return value.
  2. If Type(value) is Object and value has a [[StringData]] internal slot, then
    1. Let s be value.[[StringData]].
    2. Assert: Type(s) is String.
    3. Return s.
  3. Throw a TypeError exception.

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

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).

When the charAt method is called with one argument pos, the following steps are taken:

  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

The charAt function 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

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.

When the charCodeAt method is called with one argument pos, the following steps are taken:

  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

The charCodeAt function 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

Returns a non-negative integral Number less than or equal to 0x10FFFF𝔽 that is the code point 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.

When the codePointAt method is called with one argument pos, the following steps are taken:

  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

The codePointAt function 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 the concat 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.

When the concat method is called with zero or more arguments, the following steps are taken:

  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 the concat method is 1𝔽.

Note 2

The concat function 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 ] )

The following steps are taken:

  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. Return ! SameValueNonNumeric(substring, searchStr).
Note 1

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 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

The endsWith function 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 ] )

The includes method takes two arguments, searchString and position, and performs the following steps:

  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 is not -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, return true; otherwise, 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

The includes function 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.

The indexOf method takes two arguments, searchString and position, and performs the following steps:

  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

The indexOf function 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.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.

The lastIndexOf method takes two arguments, searchString and position, and performs the following steps:

  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 start be the result of clamping pos between 0 and len.
  9. Let searchLen be the length of searchStr.
  10. Let k be the largest possible non-negative integer not larger than start such that k + searchLenlen, and for all non-negative integers j such that j < searchLen, the code unit at index k + j within S is the same as the code unit at index j within searchStr; but if there is no such integer, let k be -1.
  11. Return 𝔽(k).
Note 2

The lastIndexOf function 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.11 String.prototype.localeCompare ( that [ , reserved1 [ , reserved2 ] ] )

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

When the localeCompare method is called with argument that, it returns a Number other than NaN that represents the result of a locale-sensitive String comparison of the this value (converted to a String) with that (converted to a String). The two Strings are S and That. The two Strings are compared in an implementation-defined fashion. The result is intended to order String values in the sort order specified by a host default locale, and will be negative, zero, or positive, depending on whether S comes before That in the sort order, the Strings are equal, or S comes after That in the sort order, respectively.

Before performing the comparisons, the following steps are performed to prepare the Strings:

  1. Let O be ? RequireObjectCoercible(this value).
  2. Let S be ? ToString(O).
  3. Let That 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 localeCompare method, if considered as a function of two arguments this and that, is a consistent comparison function (as defined in 23.1.3.28) on the set of all Strings.

The actual return values are implementation-defined to permit implementers to encode additional information in the value, but the function is required to define a total ordering on all Strings. This function must treat Strings that are canonically equivalent according to the Unicode standard as identical and must return 0 when comparing Strings that are considered canonically equivalent.

Note 1

The localeCompare 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 function is intended to rely on whatever language-sensitive comparison functionality is available to the ECMAScript environment from the host environment, and to compare according to the rules of the host environment's current locale. However, regardless of the host provided comparison capabilities, this function must treat Strings that are canonically equivalent according to the Unicode standard as identical. It is recommended that this function should not honour Unicode compatibility equivalences or decompositions. 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 (https://unicode.org/reports/tr15/) and Unicode Technical Note #5, Canonical Equivalence in Applications (https://www.unicode.org/notes/tn5/). Also see Unicode Technical Standard #10, Unicode Collation Algorithm (https://unicode.org/reports/tr10/).

Note 3

The localeCompare function 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.match ( regexp )

When the match method is called with argument regexp, the following steps are taken:

  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

The match function 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.matchAll ( regexp )

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.

When the matchAll method is called, the following steps are taken:

  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
The matchAll function 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.14 String.prototype.normalize ( [ form ] )

When the normalize method is called with one argument form, the following steps are taken:

  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 https://unicode.org/reports/tr15/.
  7. Return ns.
Note

The normalize function 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.15 String.prototype.padEnd ( maxLength [ , fillString ] )

When the padEnd method is called, the following steps are taken:

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

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

When the padStart method is called, the following steps are taken:

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

22.1.3.16.1 StringPad ( O, maxLength, fillString, placement )

The abstract operation StringPad takes arguments O (an ECMAScript language value), maxLength (an ECMAScript language value), fillString (an ECMAScript language value), and placement (start or end). 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, let filler be the String value consisting solely of the code unit 0x0020 (SPACE).
  6. Else, let filler be ? ToString(fillString).
  7. If filler is the empty String, return S.
  8. Let fillLen be intMaxLength - stringLength.
  9. Let truncatedStringFiller be the String value consisting of repeated concatenations of filler truncated to length fillLen.
  10. If placement is start, return the string-concatenation of truncatedStringFiller and S.
  11. 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 String.prototype.repeat ( count )

The following steps are taken:

  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 is +∞, throw a RangeError exception.
  5. If n is 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

The repeat function 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.18 String.prototype.replace ( searchValue, replaceValue )

When the replace method is called with arguments searchValue and replaceValue, the following steps are taken:

  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 is -1, return string.
  10. Let preserved be the substring of string from 0 to position.
  11. If functionalReplace is true, then
    1. Let replacement be ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(position), string »)).
  12. Else,
    1. Assert: Type(replaceValue) is String.
    2. Let captures be a new empty List.
    3. Let replacement be ! GetSubstitution(searchString, string, position, captures, undefined, replaceValue).
  13. Return the string-concatenation of preserved, replacement, and the substring of string from position + searchLength.
Note

The replace function 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.18.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacement )

The abstract operation GetSubstitution takes arguments matched (a String), str (a String), position (a non-negative integer), captures (a possibly empty List of Strings), namedCaptures (an Object or undefined), and replacement (a String). It performs the following steps when called:

  1. Let matchLength be the number of code units in matched.
  2. Let stringLength be the number of code units in str.
  3. Assert: positionstringLength.
  4. Let tailPos be position + matchLength.
  5. Let m be the number of elements in captures.
  6. Let result be the String value derived from replacement by copying code unit elements from replacement to result while performing replacements as specified in Table 67. These $ replacements are done left-to-right, and, once such a replacement is performed, the new replacement text is not subject to further replacements.
  7. Return result.
Table 67: Replacement Text Symbol Substitutions
Code units Unicode Characters Replacement text
0x0024, 0x0024 $$ $
0x0024, 0x0026 $& matched
0x0024, 0x0060 $` The replacement is the substring of str from 0 to position.
0x0024, 0x0027 $' If tailPosstringLength, the replacement is the empty String. Otherwise the replacement is the substring of str from tailPos.
0x0024, N
Where
0x0031 ≤ N ≤ 0x0039
$n where
n is one of 1 2 3 4 5 6 7 8 9 and $n is not followed by a decimal digit
The nth element of captures, where n is a single digit in the range 1 to 9. If nm and the nth element of captures is undefined, use the empty String instead. If n > m, no replacement is done.
0x0024, N, N
Where
0x0030 ≤ N ≤ 0x0039
$nn where
n is one of 0 1 2 3 4 5 6 7 8 9
The nnth element of captures, where nn is a two-digit decimal number in the range 01 to 99. If nnm and the nnth element of captures is undefined, use the empty String instead. If nn is 00 or nn > m, no replacement is done.
0x0024, 0x003C $<
  1. If namedCaptures is undefined, the replacement text is the String "$<".
  2. Else,
    1. Assert: Type(namedCaptures) is Object.
    2. Scan until the next > U+003E (GREATER-THAN SIGN).
    3. If none is found, the replacement text is the String "$<".
    4. Else,
      1. Let groupName be the enclosed substring.
      2. Let capture be ? Get(namedCaptures, groupName).
      3. If capture is undefined, replace the text through > with the empty String.
      4. Otherwise, replace the text through > with ? ToString(capture).
0x0024 $ in any context that does not match any of the above. $

22.1.3.19 String.prototype.replaceAll ( searchValue, replaceValue )

When the replaceAll method is called with arguments searchValue and replaceValue, the following steps are taken:

  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 is not -1,
    1. Append position to the end of 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: Type(replaceValue) is 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.20 String.prototype.search ( regexp )

When the search method is called with argument regexp, the following steps are taken:

  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

The search function 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.21 String.prototype.slice ( start, end )

The slice method takes two arguments, start and end, and 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. The following steps are taken:

  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 is -∞, 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 is -∞, 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

The slice function 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.split ( separator, limit )

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.

When the split method is called, the following steps are taken:

  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. Let A be ! ArrayCreate(0).
  5. Let lengthA be 0.
  6. If limit is undefined, let lim be 232 - 1; else let lim be (? ToUint32(limit)).
  7. Let R be ? ToString(separator).
  8. If lim = 0, return A.
  9. If separator is undefined, then
    1. Perform ! CreateDataPropertyOrThrow(A, "0", S).
    2. Return A.
  10. Let s be the length of S.
  11. If s = 0, then
    1. If R is not the empty String, then
      1. Perform ! CreateDataPropertyOrThrow(A, "0", S).
    2. Return A.
  12. Let p be 0.
  13. Let q be p.
  14. Repeat, while qs,
    1. Let e be SplitMatch(S, q, R).
    2. If e is not-matched, set q to q + 1.
    3. Else,
      1. Assert: e is a non-negative integers.
      2. If e = p, set q to q + 1.
      3. Else,
        1. Let T be the substring of S from p to q.
        2. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), T).
        3. Set lengthA to lengthA + 1.
        4. If lengthA = lim, return A.
        5. Set p to e.
        6. Set q to p.
  15. Let T be the substring of S from p to s.
  16. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), T).
  17. Return A.
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

The split function 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.1 SplitMatch ( S, q, R )

The abstract operation SplitMatch takes arguments S (a String), q (a non-negative integer), and R (a String). It returns either not-matched or the end index of a match. It performs the following steps when called:

  1. Let r be the number of code units in R.
  2. Let s be the number of code units in S.
  3. If q + r > s, return not-matched.
  4. If there exists an integer i between 0 (inclusive) and r (exclusive) such that the code unit at index q + i within S is different from the code unit at index i within R, return not-matched.
  5. Return q + r.

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

The following steps are taken:

  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. Return ! SameValueNonNumeric(substring, searchStr).
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 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

The startsWith function 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.substring ( start, end )

The substring method takes two arguments, start and end, and 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 larger than the length of the String, it is replaced with the length of the String.

If start is larger than end, they are swapped.

The following steps are taken:

  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

The substring function 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.toLocaleLowerCase ( [ reserved1 [ , reserved2 ] ] )

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

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

This function works exactly the same as toLowerCase except that its result is intended to yield the correct result for the host environment's current locale, rather than a locale-independent result. 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

The toLocaleLowerCase function 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.toLocaleUpperCase ( [ reserved1 [ , reserved2 ] ] )

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

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

This function works exactly the same as toUpperCase except that its result is intended to yield the correct result for the host environment's current locale, rather than a locale-independent result. 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

The toLocaleUpperCase function 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.toLowerCase ( )

This function interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4. The following steps are taken:

  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 UnicodeData.txt file, but also all locale-insensitive mappings in the SpecialCasings.txt file 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 functions are not symmetrical. In other words, s.toUpperCase().toLowerCase() is not necessarily equal to s.toLowerCase().

Note 2

The toLowerCase function 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.toString ( )

When the toString method is called, the following steps are taken:

  1. Return ? thisStringValue(this value).
Note

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

22.1.3.29 String.prototype.toUpperCase ( )

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

This function 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

The toUpperCase function 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.30 String.prototype.trim ( )

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

The following steps are taken:

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

The trim function 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.30.1 TrimString ( string, where )

The abstract operation TrimString takes arguments string (an ECMAScript language value) and where (start, end, or start+end). 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, let T be the String value that is a copy of S with leading white space removed.
  4. Else if where is end, 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.31 String.prototype.trimEnd ( )

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

The following steps are taken:

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

The trimEnd function 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 String.prototype.trimStart ( )

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

The following steps are taken:

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

The trimStart function 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.33 String.prototype.valueOf ( )

When the valueOf method is called, the following steps are taken:

  1. Return ? thisStringValue(this value).

22.1.3.34 String.prototype [ @@iterator ] ( )

When the @@iterator method is called it 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. The following steps are taken:

  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 position be 0.
    2. Let len be the length of s.
    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 ? Yield(resultString).
    4. Return undefined.
  4. Return ! CreateIteratorFromClosure(closure, "%StringIteratorPrototype%", %StringIteratorPrototype%).

The value of the "name" property of this function 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.

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 }.