Strings API Flashcards

1
Q

String.prototype[@@iterator]()

A

The [@@iterator]() method of String values implements the iterable protocol and allows strings to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns a string iterator object that yields the Unicode code points of the string value as individual strings.

Note: Strings are iterated by Unicode code points. This means grapheme clusters will be split, but surrogate pairs will be preserved.

Note2: You seldom need to call this method directly. The existence of the @@iterator method makes strings iterable, and iterating syntaxes like the for...of loop automatically call this method to obtain the iterator to loop over.

// "Backhand Index Pointing Right: Dark Skin Tone"
[..."👉🏿"]; // ['👉', '🏿']
// splits into the basic "Backhand Index Pointing Right" emoji and
// the "Dark skin tone" emoji

// "Family: Man, Boy"
[..."👨‍👦"]; // [ '👨', '‍', '👦' ]
// splits into the "Man" and "Boy" emoji, joined by a ZWJ

Syntax

string[Symbol.iterator]()

Parameters
None.

Return value
A new iterable iterator object that yields the Unicode code points of the string value as individual strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

String.prototype.charAt()

A

The charAt() method of String values returns a new string consisting of the single UTF-16 code unit at the given index.

Unicode code points range from 0 to 1114111 (0x10FFFF). charAt() always returns a character whose value is less than 65536, because the higher code points are represented by a pair of 16-bit surrogate pseudo-characters. Therefore, in order to get a full character with value greater than 65535, it is necessary to retrieve not only charAt(i), but also charAt(i + 1) (as if manipulating a string with two characters), or to use codePointAt(i) and String.fromCodePoint() instead. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

Syntax

charAt(index)

Parameters

index - Zero-based index of the character to be returned. Converted to an integer — undefined is converted to 0.

Return value
A string representing the character (exactly one UTF-16 code unit) at the specified index. If index is out of the range of 0 – str.length - 1, charAt() returns an empty string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

String.prototype.charCodeAt()

A

The charCodeAt() method of String values returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

charCodeAt() always indexes the string as a sequence of UTF-16 code units, so it may return lone surrogates. To get the full Unicode code point at the given index, use String.prototype.codePointAt().

Syntax

charCodeAt(index)

Parameters

  • index - Zero-based index of the character to be returned. Converted to an integerundefined is converted to 0.

Return value
An integer between 0 and 65535 representing the UTF-16 code unit value of the character at the specified index. If index is out of range of 0 – str.length - 1, charCodeAt() returns NaN.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

String.prototype.codePointAt()

A

The codePointAt() method of String values returns a non-negative integer that is the Unicode code point value of the character starting at the given index. Note that the index is still based on UTF-16 code units, not Unicode code points.

Syntax

codePointAt(index)

Parameters

index Zero-based index of the character to be returned. Converted to an integer — undefined is converted to 0.

Return value
A non-negative integer representing the code point value of the character at the given index.

  • If index is out of the range of 0 – str.length - 1, codePointAt() returns undefined.
  • If the element at index is a UTF-16 leading surrogate, returns the code point of the surrogate pair.
  • If the element at index is a UTF-16 trailing surrogate, returns only the trailing surrogate code unit.

Example

"ABC".codePointAt(0); // 65
"ABC".codePointAt(0).toString(16); // 41

"😍".codePointAt(0); // 128525
"\ud83d\ude0d".codePointAt(0); // 128525
"\ud83d\ude0d".codePointAt(0).toString(16); // 1f60d

"😍".codePointAt(1); // 56845
"\ud83d\ude0d".codePointAt(1); // 56845
"\ud83d\ude0d".codePointAt(1).toString(16); // de0d

"ABC".codePointAt(42); // undefined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

String.prototype.concat()

A

The concat() method of String values, concatenates the string arguments to the calling string and returns a new string.

If the arguments are not of the type string, they are converted to string values before concatenating.

The concat() method is very similar to the addition/string concatenation operators (+, +=), except that concat() coerces its arguments directly to strings, while addition coerces its operands to primitives first.

Syntax

concat()
concat(str1)
concat(str1, str2)
concat(str1, str2, /* …, */ strN)

Parameters
str1, …, strN - One or more strings to concatenate to str.

Return value
A new string containing the combined text of the strings provided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

String.prototype.endsWith()

A

The endsWith() method of String values, lets you determine whether or not a string ends with another string. This method is case-sensitive.

Syntax

endsWith(searchString)
endsWith(searchString, endPosition)

Parameters

  • searchString - The characters to be searched for at the end of str. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes endsWith() to search for the string "undefined", which is rarely what you want.
  • endPosition Optional - The end position at which searchString is expected to be found (the index of searchString’s last character plus 1). Defaults to str.length.

Return value
true if the given characters are found at the end of the string, including when searchString is an empty string; otherwise, false.

Exceptions
TypeError - Thrown if searchString is a regex.

Examples

const str = "To be, or not to be, that is the question.";

console.log(str.endsWith("question.")); // true
console.log(str.endsWith("to be")); // false
console.log(str.endsWith("to be", 19)); // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

String.fromCharCode()

A

The String.fromCharCode() static method returns a string created from the specified sequence of UTF-16 code units.

NOTE: Unicode code points range from 0 to 1114111 (0x10FFFF). charCodeAt() always returns a value that is less than 65536, because the higher code points are represented by a pair of 16-bit surrogate pseudo-characters. Therefore, in order to produce a full character with value greater than 65535, it is necessary to provide two code units (as if manipulating a string with two characters). For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

Syntax

String.fromCharCode()
String.fromCharCode(num1)
String.fromCharCode(num1, num2)
String.fromCharCode(num1, num2, /* …, */ numN)

Parameters

  • num1, …, numN - A number between 0 and 65535 (0xFFFF) representing a UTF-16 code unit. Numbers greater than 0xFFFF are truncated to the last 16 bits. No validity checks are performed.

Return value
A string of length N consisting of the N specified UTF-16 code units.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

String.fromCodePoint()

A

The String.fromCodePoint() static method returns a string created from the specified sequence of code points.

Syntax

String.fromCodePoint()
String.fromCodePoint(num1)
String.fromCodePoint(num1, num2)
String.fromCodePoint(num1, num2, /* …, */ numN)

Parameters
num1, …, numN - An integer between 0 and 0x10FFFF (inclusive) representing a Unicode code point.

Return value
A string created by using the specified sequence of code points.

Exceptions
RangeError - Thrown if numN is not an integer, is less than 0, or is greater than 0x10FFFF after being converted to a number.

Examples

String.fromCodePoint(42); // "*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // "\u0404" === "Є"
String.fromCodePoint(0x2f804); // "\uD87E\uDC04"
String.fromCodePoint(194564); // "\uD87E\uDC04"
String.fromCodePoint(0x1d306, 0x61, 0x1d307); // "\uD834\uDF06a\uD834\uDF07"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

String.prototype.includes()

A

The includes() method of String values performs a case-sensitive search to determine whether a given string may be found within this string, returning true or false as appropriate.

Syntax

includes(searchString)
includes(searchString, position)

Parameters

  • searchString - A string to be searched for within str. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes includes() to search for the string “undefined”, which is rarely what you want.
  • position Optional - The position within the string at which to begin searching for searchString. (Defaults to 0.)

Return value
true if the search string is found anywhere within the given string, including when searchString is an empty string; otherwise, false.

Exceptions
TypeError - Thrown if searchString is a regex.

Examples

const str = "To be, or not to be, that is the question.";

console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("nonexistent")); // false
console.log(str.includes("To be", 1)); // false
console.log(str.includes("TO BE")); // false
console.log(str.includes("")); // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

String.prototype.indexOf()

A

The indexOf() method of String values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

Syntax

indexOf(searchString)
indexOf(searchString, position)

Parameters

searchString - Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes indexOf() to search for the string "undefined", which is rarely what you want.

position Optional - The method returns the index of the first occurrence of the specified substring at a position greater than or equal to position, which defaults to 0. If position is greater than the length of the calling string, the method doesn’t search the calling string at all. If position is less than zero, the method behaves as it would if position were 0:

  • 'hello world hello'.indexOf('o', -5) returns 4 — because it causes the method to behave as if the second argument were 0, and the first occurrence of o at a position greater or equal to 0 is at position 4.
  • 'hello world hello'.indexOf('world', 12) returns -1 — because, while it’s true the substring world occurs at index 6, that position is not greater than or equal to 12.
  • 'hello world hello'.indexOf('o', 99) returns -1 — because 99 is greater than the length of hello world hello, which causes the method to not search the string at all.

Return value

  • The index of the first occurrence of searchString found, or -1 if not found.

Examples:

"hello world".indexOf(""); // returns 0
"hello world".indexOf("", 0); // returns 0
"hello world".indexOf("", 3); // returns 3
"hello world".indexOf("", 8); // returns 8
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

String.prototype.isWellFormed()

A

The isWellFormed() method of String values returns a boolean indicating whether this string contains any lone surrogates.

Syntax

isWellFormed()

Parameters
None.

Return value
Returns true if this string does not contain any lone surrogates, false otherwise.

Examples

const strings = [
  // Lone leading surrogate
  "ab\uD800",
  "ab\uD800c",
  // Lone trailing surrogate
  "\uDFFFab",
  "c\uDFFFab",
  // Well-formed
  "abc",
  "ab\uD83D\uDE04c",
];

for (const str of strings) {
  console.log(str.isWellFormed());
}
// Logs:
// false
// false
// false
// false
// true
// true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

String.prototype.localeCompare()

A

The localeCompare() method of String values returns an integer indicating whether the referenceStr (aka the this value string) string comes before, after or is equivalent to the compared string.

  • Negative when the referenceStr occurs before compareString
  • Positive when the referenceStr occurs after compareString
  • Returns 0 if they are equivalent

Warning: Do not rely on exact return values of -1 or 1! Negative and positive integer results vary between browsers (as well as between browser versions) because the ECMAScript specification only mandates negative and positive values. Some browsers may return -2 or 2, or even some other negative or positive value.

Syntax

localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, locales, options)

Parameters
The locales and options parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.Collator API, these parameters correspond exactly to the Intl.Collator() constructor’s parameters. Implementations without Intl.Collator support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it’s only required to be consistent.

  • compareString - The string against which the referenceStr is compared. All values are coerced to strings, so omitting it or passing undefined causes localeCompare() to compare against the string "undefined", which is rarely what you want.
  • locales Optional - A string with a BCP 47 language tag, or an array of such strings. Corresponds to the locales parameter of the Intl.Collator() constructor.
  • options Optional - An object adjusting the output format. Corresponds to the options parameter of the Intl.Collator() constructor.

Return value
A negative number if referenceStr occurs before compareString; positive if the referenceStr occurs after compareString; 0 if they are equivalent.

In implementations with Intl.Collator, this is equivalent to new Intl.Collator(locales, options).compare(referenceStr, compareString).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

String.prototype.match()

A

The match() method of String values retrieves the result of matching this string against a regular expression.

Syntax

match(regexp)

Parameters

regexp - A regular expression object, or any object that has a Symbol.match method.

  • If regexp is not a RegExp object and does not have a Symbol.match method, it is implicitly converted to a RegExp by using new RegExp(regexp).
  • If you don’t give any parameter and use the match() method directly, you will get an Array with an empty string: [""], because this is equivalent to match(/(?:)/).

Return value
An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

  • If the g flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included.
  • If the g flag is not used, only the first complete match and its related capturing groups are returned. In this case, match() will return the same result as RegExp.prototype.exec() (an array with some extra properties).

Examples

const str = "For more information, see Chapter 3.4.5.1";
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);

console.log(found);
// [
//   'see Chapter 3.4.5.1',
//   'Chapter 3.4.5.1',
//   '.1',
//   index: 22,
//   input: 'For more information, see Chapter 3.4.5.1',
//   groups: undefined
// ]

// Examples with global (`g`) and ignoreCase (`i`) flags
const str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const regexp = /[A-E]/gi;
const matches = str.match(regexp);

console.log(matches);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

String.prototype.matchAll()

A

The matchAll() method of String values returns an iterator of all results matching this string against a regular expression, including capturing groups.

Syntax

matchAll(regexp)

Parameters

regexp - A regular expression object, or any object that has a Symbol.matchAll method.

  • If regexp is not a RegExp object and does not have a Symbol.matchAll method, it is implicitly converted to a RegExp by using new RegExp(regexp, 'g').
  • If regexp is a regex, then it must have the global (g) flag set, or a TypeError is thrown.

Return value

  • An iterable iterator object (which is not restartable) of matches or an empty iterator if no matches are found. Each value yielded by the iterator is an array with the same shape as the return value of RegExp.prototype.exec().

Exceptions

  • TypeError - Thrown if the regexp is a regex that does not have the global (g) flag set (its flags property does not contain "g").

Example

const regexp = /foo[a-z]*/g;
const str = "table football, foosball";
const matches = str.matchAll(regexp);

for (const match of matches) {
  console.log(
    `Found ${match[0]} start=${match.index} end=${
      match.index + match[0].length
    }.`,
  );
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.

// matches iterator is exhausted after the for...of iteration
// Call matchAll again to create a new iterator
Array.from(str.matchAll(regexp), (m) => m[0]);
// [ "football", "foosball" ]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

String.prototype.normalize()

A

The normalize() method of String values returns the Unicode Normalization Form of this string.

Unicode assigns a unique numerical value, called a code point, to each character. For example, the code point for "A" is given as U+0041. However, sometimes more than one code point, or sequence of code points, can represent the same abstract character — the character "ñ" for example can be represented by either of:

The single code point U+00F1.
The code point for “n” (U+006E) followed by the code point for the combining tilde (U+0303).

const string1 = "\u00F1";
const string2 = "\u006E\u0303";

console.log(string1); // ñ
console.log(string2); // ñ

However, since the code points are different, string comparison will not treat them as equal. And since the number of code points in each version is different, they even have different lengths.

const string1 = "\u00F1"; // ñ
const string2 = "\u006E\u0303"; // ñ

console.log(string1 === string2); // false
console.log(string1.length); // 1
console.log(string2.length); // 2

The normalize() method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters. There are two main normalization forms, one based on canonical equivalence and the other based on compatibility.

let string1 = "\u00F1"; // ñ
let string2 = "\u006E\u0303"; // ñ

string1 = string1.normalize("NFD");
string2 = string2.normalize("NFD");

console.log(string1 === string2); // true
console.log(string1.length); // 2
console.log(string2.length); // 2

Syntax

normalize()
normalize(form)

Parameters

form Optional - One of "NFC", "NFD", "NFKC", or "NFKD", specifying the Unicode Normalization Form. If omitted or undefined, "NFC" is used.

These values have the following meanings:

  • "NFC" - Canonical Decomposition, followed by Canonical Composition.
  • "NFD" - Canonical Decomposition.
  • "NFKC" - Compatibility Decomposition, followed by Canonical Composition.
  • "NFKD" - Compatibility Decomposition.

Return value
A string containing the Unicode Normalization Form of the given string.

Exceptions

  • RangeError - Thrown if form isn’t one of the values specified above.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

String.prototype.padEnd()

A

The padEnd() method of String values pads this string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of this string.

Syntax

padEnd(targetLength)
padEnd(targetLength, padString)

Parameters

  • targetLength - The length of the resulting string once the current str has been padded. If the value is less than or equal to str.length, the current string will be returned as-is.
  • padString Optional - The string to pad the current str with. If padString is too long to stay within targetLength, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. The default value for this parameter is the unicode space character " " (U+0020).

Return value

  • A String of the specified targetLength with the padString applied at the end of the current str.

Examples

"abc".padEnd(10); // "abc       "
"abc".padEnd(10, "foo"); // "abcfoofoof"
"abc".padEnd(6, "123456"); // "abc123"
"abc".padEnd(1); // "abc"
17
Q

String.prototype.padStart()

A

The padStart() method of String values pads this string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of this string.

Syntax

padStart(targetLength)
padStart(targetLength, padString)

Parameters

  • targetLength - The length of the resulting string once the current str has been padded. If the value is less than or equal to str.length, then str is returned as-is.
  • padString Optional - The string to pad the current str with. If padString is too long to stay within the targetLength, it will be truncated from the end. The default value is the unicode space character " " (U+0020).

Return value
A String of the specified targetLength with padString applied from the start.

Examples

"abc".padStart(10); // "       abc"
"abc".padStart(10, "foo"); // "foofoofabc"
"abc".padStart(6, "123465"); // "123abc"
"abc".padStart(8, "0"); // "00000abc"
"abc".padStart(1); // "abc"
18
Q

String.raw()

A

The String.raw() static method is a tag function of template literals. It’s used to get the raw string form of template literals — that is, substitutions (e.g. ${foo}) are processed, but escape sequences (e.g. \n) are not.

Syntax

String.raw(strings)
String.raw(strings, sub1)
String.raw(strings, sub1, sub2)
String.raw(strings, sub1, sub2, /* …, */ subN)

String.raw`templateString`

Parameters

  • strings - Well-formed template literal array object, like { raw: ['foo', 'bar', 'baz'] }. Should be an object with a raw property whose value is an array-like object of strings.
  • sub1, …, subN - Contains substitution values.
  • templateString - A template literal, optionally with substitutions (${...}).

Return value

  • The raw string form of a given template literal.

Exceptions

  • TypeError Thrown if the first argument doesn’t have a raw property, or the raw property is undefined or null.

Examples

String.raw`Hi\n${2 + 3}!`;
// 'Hi\\n5!', the character after 'Hi'
// is not a newline character,
// '\' and 'n' are two characters.

String.raw`Hi\u000A!`;
// 'Hi\\u000A!', same here, this time we will get the
// \, u, 0, 0, 0, A, 6 characters.
// All kinds of escape characters will be ineffective
// and backslashes will be present in the output string.
// You can confirm this by checking the .length property
// of the string.

const name = "Bob";
String.raw`Hi\n${name}!`;
// 'Hi\\nBob!', substitutions are processed.

String.raw`Hi \${name}!`;
// 'Hi \\${name}!', the dollar sign is escaped; there's no interpolation.
19
Q

String.prototype.repeat()

A

The repeat() method of String values constructs and returns a new string which contains the specified number of copies of this string, concatenated together.

Syntax

repeat(count)

Parameters

  • count - An integer between 0 and +Infinity, indicating the number of times to repeat the string.

Return value

  • A new string containing the specified number of copies of the given string.

Exceptions

  • RangeError - Thrown if count is negative or if count overflows maximum string length.

Examples

"abc".repeat(-1); // RangeError
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
"abc".repeat(1 / 0); // RangeError

({ toString: () => "abc", repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)
20
Q

String.prototype.replace()

A

The replace() method of String values returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

Syntax

replace(pattern, replacement)

Parameters

pattern - Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn’t have the Symbol.replace method will be coerced to a string.
replacement - Can be a string or a function.

replacement as string patterns

The replacement string can include the following special replacement patterns:

Pattern Inserts:

  • $$ Inserts a "$".
  • $& Inserts the matched substring.
  • $` Inserts the portion of the string that precedes the matched substring.
  • $' Inserts the portion of the string that follows the matched substring.
  • $n Inserts the nth (1-indexed) capturing group where n is a positive integer less than 100.
  • $<Name> Inserts the named capturing group where Name is the group name.

$n and $<Name> are only available if the pattern argument is a RegExp object. If the pattern is a string, or if the corresponding capturing group isn’t present in the regex, then the pattern will be replaced as a literal. If the group is present but isn’t matched (because it’s part of a disjunction), it will be replaced with an empty string.

"foo".replace(/(f)/, "$2");
// "$2oo"; the regex doesn't have the second group

"foo".replace("f", "$1");
// "$1oo"; the pattern is a string, so it doesn't have any groups

"foo".replace(/(f)|(g)/, "$2");
// "oo"; the second group exists but isn't matched

replacement as a function

The function has the following signature:

function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
  return replacement;
}

The arguments to the function are as follows:

  • match - The matched substring. (Corresponds to $& above.)
  • p1, p2, …, pN - The nth string found by a capture group (including named capturing groups), provided the first argument to replace() is a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if the pattern is /(\a+)(\b+)/, then p1 is the match for \a+, and p2 is the match for \b+. If the group is part of a disjunction (e.g. "abc".replace(/(a)|(b)/, replacer)), the unmatched alternative will be undefined.
  • offset - The offset of the matched substring within the whole string being examined. For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.
  • string - The whole string being examined.
  • groups - An object whose keys are the used group names, and whose values are the matched portions (undefined if not matched). Only present if the pattern contains at least one named capturing group.

The exact number of arguments depends on whether the first argument is a RegExp object — and, if so, how many capture groups it has.

The following example will set newString to 'abc - 12345 - #$*%':

function replacer(match, p1, p2, p3, offset, string) {
  // p1 is non-digits, p2 digits, and p3 non-alphanumerics
  return [p1, p2, p3].join(" - ");
}
const newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%

Return value
A new string, with one, some, or all matches of the pattern replaced by the specified replacement.

21
Q

String.prototype.replaceAll()

A

The replaceAll() method of String values returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

Syntax

replaceAll(pattern, replacement)

Parameters

  • pattern - Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn’t have the Symbol.replace method will be coerced to a string.
    If pattern is a regex, then it must have the global (g) flag set, or a TypeError is thrown.
  • replacement - Can be a string or a function. The replacement has the same semantics as that of String.prototype.replace().

Return value

  • A new string, with all matches of a pattern replaced by a replacement.

Exceptions

  • TypeError - Thrown if the pattern is a regex that does not have the global (g) flag set (its flags property does not contain “g”).

Examples:

"xxx".replaceAll("", "_"); // "_x_x_x_"

"aabbcc".replaceAll(/b/g, ".");
("aa..cc");

"aabbcc".replaceAll(/b/, ".");
// TypeError: replaceAll must be called with a global RegExp
22
Q

String.prototype.search()

A

The search() method of String values executes a search for a match between a regular expression and this string, returning the index of the first match in the string.

Syntax

search(regexp)

Parameters

  • regexp - A regular expression object, or any object that has a Symbol.search method.
    If regexp is not a RegExp object and does not have a Symbol.search method, it is implicitly converted to a RegExp by using new RegExp(regexp).

Return value

  • The index of the first match between the regular expression and the given string, or -1 if no match was found.

Examples:

const str = "hey JudE";
const re = /[A-Z]/;
const reDot = /[.]/;
console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation
23
Q

String.prototype.slice()

A

The slice() method of String values extracts a section of this string and returns it as a new string, without modifying the original string.

Syntax

slice(indexStart)
slice(indexStart, indexEnd)

Parameters

  • indexStart - The index of the first character to include in the returned substring.
  • indexEnd Optional - The index of the first character to exclude from the returned substring.

Return value

  • A new string containing the extracted section of the string.

Description

slice() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

slice() extracts up to but not including indexEnd. For example, str.slice(4, 8) extracts the fifth character through the eighth character (characters indexed 4, 5, 6, and 7):

  • If indexStart >= str.length, an empty string is returned.
  • If indexStart < 0, the index is counted from the end of the string. More formally, in this case, the substring starts at max(indexStart + str.length, 0).
  • If indexStart is omitted, undefined, or cannot be converted to a number, it’s treated as 0.
  • If indexEnd is omitted, undefined, or cannot be converted to a number, or if indexEnd >= str.length, slice() extracts to the end of the string.
  • If indexEnd < 0, the index is counted from the end of the string. More formally, in this case, the substring ends at max(indexEnd + str.length, 0).
  • If indexEnd <= indexStart after normalizing negative values (i.e. indexEnd represents a character that’s before indexStart), an empty string is returned.

Examples:

const str1 = "The morning is upon us."; // The length of str1 is 23.
const str2 = str1.slice(1, 8);
const str3 = str1.slice(4, -2);
const str4 = str1.slice(12);
const str5 = str1.slice(30);
console.log(str2); // he morn
console.log(str3); // morning is upon u
console.log(str4); // is upon us.
console.log(str5); // ""
24
Q

String.prototype.split()

A

The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

Syntax

split(separator)
split(separator, limit)

Parameters
separator - The pattern describing where each split should occur. Can be undefined, a string, or an object with a Symbol.split method — the typical example being a regular expression. Omitting separator or passing undefined causes split() to return an array with the calling string as a single element. All values that are not undefined or objects with a @@split method are coerced to strings.

limit Optional - A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

  • The array may contain fewer entries than limit if the end of the string is reached before the limit is reached.
  • If limit is 0, [] is returned.

Return value

  • An Array of strings, split at each point where the separator occurs in the given string.

Note: If separator is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode code points depends on if the regex is Unicode-aware.

"😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ]
"😄😄".split(/(?:)/u); // [ "😄", "😄" ]

Examples:

const emptyString = "";

// string is empty and separator is non-empty
console.log(emptyString.split("a"));
// [""]

// string and separator are both empty strings
console.log(emptyString.split(emptyString));
// []
25
Q

String.prototype.startsWith()

A

The startsWith() method of String values determines whether this string begins with the characters of a specified string, returning true or false as appropriate.

Syntax

startsWith(searchString)
startsWith(searchString, position)

Parameters

  • searchString - The characters to be searched for at the start of this string. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes startsWith() to search for the string "undefined", which is rarely what you want.
  • position Optional - The start position at which searchString is expected to be found (the index of searchString’s first character). Defaults to 0.

Return value

  • true if the given characters are found at the beginning of the string, including when searchString is an empty string; otherwise, false.

Exceptions

Examples:

const str = "To be, or not to be, that is the question.";

console.log(str.startsWith("To be")); // true
console.log(str.startsWith("not to be")); // false
console.log(str.startsWith("not to be", 10)); // true
26
Q

String.prototype.substring()

A

The substring() method of String values returns the part of this string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied.

Syntax

substring(indexStart)
substring(indexStart, indexEnd)

Parameters

  • indexStart - The index of the first character to include in the returned substring.
  • indexEnd Optional - The index of the first character to exclude from the returned substring.

Return value

  • A new string containing the specified part of the given string.

Description
substring() extracts characters from indexStart up to but not including indexEnd. In particular:

  • If indexEnd is omitted, substring() extracts characters to the end of the string.
  • If indexStart is equal to indexEnd, substring() returns an empty string.
  • If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped;
  • Any argument value that is less than 0 or greater than str.length is treated as if it were 0 and str.length, respectively.
  • Any argument value that is NaN is treated as if it were 0.

Examples:

const anyString = "Mozilla";

console.log(anyString.substring(0, 1)); // "M"
console.log(anyString.substring(1, 0)); // "M"

console.log(anyString.substring(0, 6)); // "Mozill"

console.log(anyString.substring(4)); // "lla"
console.log(anyString.substring(4, 7)); // "lla"
console.log(anyString.substring(7, 4)); // "lla"

console.log(anyString.substring(0, 7)); // "Mozilla"
console.log(anyString.substring(0, 10)); // "Mozilla"
27
Q

String.prototype.toLocaleLowerCase()

A

The toLocaleLowerCase() method of String values returns this string converted to lower case, according to any locale-specific case mappings.

The toLocaleLowerCase() method returns the value of the string converted to lower case according to any locale-specific case mappings. toLocaleLowerCase() does not affect the value of the string itself. In most cases, this will produce the same result as toLowerCase(), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.

Syntax

toLocaleLowerCase()
toLocaleLowerCase(locales)

Parameters

  • locales Optional - A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to lower case according to any locale-specific case mappings.

Return value

  • A new string representing the calling string converted to lower case, according to any locale-specific case mappings.

Examples:

"ALPHABET".toLocaleLowerCase(); // 'alphabet'

"\u0130".toLocaleLowerCase("tr") === "i"; // true
"\u0130".toLocaleLowerCase("en-US") === "i"; // false

const locales = ["tr", "TR", "tr-TR", "tr-u-co-search", "tr-x-turkish"];
"\u0130".toLocaleLowerCase(locales) === "i"; // true
28
Q

String.prototype.toLocaleUpperCase()

A

The toLocaleUpperCase() method of String values returns this string converted to upper case, according to any locale-specific case mappings.

Syntax

toLocaleUpperCase()
toLocaleUpperCase(locales)

Parameters

  • locales Optional - A string with a BCP 47 language tag, or an array of such strings. Indicates the locale to be used to convert to upper case according to any locale-specific case mappings. For the general form and interpretation of the locales argument, see the parameter description on the Intl main page.

Unlike other methods that use the locales argument, toLocaleUpperCase() does not allow locale matching. Therefore, after checking the validity of the locales argument, toLocaleUpperCase() always uses the first locale in the list (or the default locale if the list is empty), even if this locale is not supported by the implementation.

Return value
A new string representing the calling string converted to upper case, according to any locale-specific case mappings.

Examples:

"alphabet".toLocaleUpperCase(); // 'ALPHABET'

"Gesäß".toLocaleUpperCase(); // 'GESÄSS'

"i\u0307".toLocaleUpperCase("lt-LT"); // 'I'

const locales = ["lt", "LT", "lt-LT", "lt-u-co-phonebk", "lt-x-lietuva"];
"i\u0307".toLocaleUpperCase(locales); // 'I'
29
Q

String.prototype.toLowerCase()

A

The toLowerCase() method of String values returns this string converted to lower case.

Syntax

toLowerCase()

Parameters
None.

Return value
A new string representing the calling string converted to lower case.

console.log("ALPHABET".toLowerCase()); // 'alphabet'
30
Q

String.prototype.toString()

A

The toString() method of String values returns this string value.

Syntax

toString()

Parameters
None.

Return value
A string representing the specified string value.

31
Q

String.prototype.toUpperCase()

A

The toUpperCase() method of String values returns this string converted to uppercase.

Syntax

toUpperCase()

Parameters
None.

Return value
A new string representing the calling string converted to upper case.

Examples:

console.log("alphabet".toUpperCase()); // 'ALPHABET'
32
Q

String.prototype.toWellFormed()

A

The toWellFormed() method of String values returns a string where all lone surrogates of this string are replaced with the Unicode replacement character U+FFFD.

Syntax

toWellFormed()

Parameters
None.

Return value
A new string that is a copy of this string, with all lone surrogates replaced with the Unicode replacement character U+FFFD. If str is well formed, a new string is still returned (essentially a copy of str).

Examples:

const strings = [
  // Lone leading surrogate
  "ab\uD800",
  "ab\uD800c",
  // Lone trailing surrogate
  "\uDFFFab",
  "c\uDFFFab",
  // Well-formed
  "abc",
  "ab\uD83D\uDE04c",
];

for (const str of strings) {
  console.log(str.toWellFormed());
}
// Logs:
// "ab�"
// "ab�c"
// "�ab"
// "c�ab"
// "abc"
// "ab😄c"
33
Q

String.prototype.trim()

A

The trim() method of String values removes whitespace from both ends of this string and returns a new string, without modifying the original string.

To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd().

Syntax

trim()

Parameters

  • None.

Return value

  • A new string representing str stripped of whitespace from both its beginning and end. Whitespace is defined as white space characters plus line terminators.
  • If neither the beginning or end of str has any whitespace, a new string is still returned (essentially a copy of str).

Examples:

const str = "   foo  ";
console.log(str.trim()); // 'foo'
34
Q

String.prototype.trimEnd()

A

The trimEnd() method of String values removes whitespace from the end of this string and returns a new string, without modifying the original string. trimRight() is an alias of this method.

Syntax

trimEnd()

Parameters

  • None.

Return value

  • A new string representing str stripped of whitespace from its end (right side). Whitespace is defined as white space characters plus line terminators.
  • If the end of str has no whitespace, a new string is still returned (essentially a copy of str).

Examples:

let str = "   foo  ";

console.log(str.length); // 8

str = str.trimEnd();
console.log(str.length); // 6
console.log(str); // '   foo'
35
Q

String.prototype.trimStart()

A

The trimStart() method of String values removes whitespace from the beginning of this string and returns a new string, without modifying the original string. trimLeft() is an alias of this method.

Syntax

trimStart()

Parameters

  • None.

Return value

  • A new string representing str stripped of whitespace from its beginning (left side). Whitespace is defined as white space characters plus line terminators.
  • If the beginning of str has no whitespace, a new string is still returned (essentially a copy of str).

Examples:

let str = "   foo  ";

console.log(str.length); // 8

str = str.trimStart();
console.log(str.length); // 5
console.log(str); // 'foo  '
36
Q

String.prototype.valueOf()

A

The valueOf() method of String returns the primitive value of a String object as a string data type. This value is equivalent to String.prototype.toString().

This method is usually called internally by JavaScript and not explicitly in code.

Syntax

valueOf()

Parameters

  • None.

Return value

  • A string representing the primitive value of a given String object.

Examples:

const x = new String("Hello world");
console.log(x.valueOf()); // 'Hello world'