String.prototype[@@iterator]()
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.
“String.prototype[@@iterator]() - JavaScript | MDN” (MDN Web Docs). Retrieved January 22, 2024.
String.prototype.charAt()
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.
“String.prototype.charAt() - JavaScript | MDN” (MDN Web Docs). Retrieved January 23, 2024.
String.prototype.charCodeAt()
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 integer β undefined 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.
“String.prototype.charCodeAt() - JavaScript | MDN” (MDN Web Docs). Retrieved January 23, 2024.
String.prototype.codePointAt()
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.
index is out of the range of 0 β str.length - 1, codePointAt() returns undefined.index is a UTF-16 leading surrogate, returns the code point of the surrogate pair.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
“String.prototype.codePointAt() - JavaScript | MDN” (MDN Web Docs). Retrieved January 23, 2024.
String.prototype.concat()
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)
Parametersstr1, β¦, strN - One or more strings to concatenate to str.
Return value
A new string containing the combined text of the strings provided.
“String.prototype.concat() - JavaScript | MDN” (MDN Web Docs). Retrieved January 23, 2024.
String.prototype.endsWith()
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 valuetrue if the given characters are found at the end of the string, including when searchString is an empty string; otherwise, false.
ExceptionsTypeError - 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“String.prototype.endsWith() - JavaScript | MDN” (MDN Web Docs). Retrieved January 24, 2024.
String.fromCharCode()
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.
“String.fromCharCode() - JavaScript | MDN” (MDN Web Docs). Retrieved January 24, 2024.
String.fromCodePoint()
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)
Parametersnum1, β¦, 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.
ExceptionsRangeError - 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"
“String.fromCodePoint() - JavaScript | MDN” (MDN Web Docs). Retrieved January 24, 2024.
String.prototype.includes()
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 valuetrue if the search string is found anywhere within the given string, including when searchString is an empty string; otherwise, false.
ExceptionsTypeError - 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“String.prototype.includes() - JavaScript | MDN” (MDN Web Docs). Retrieved January 24, 2024.
String.prototype.indexOf()
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
-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“String.prototype.indexOf() - JavaScript | MDN” (MDN Web Docs). Retrieved January 25, 2024.
String.prototype.isWellFormed()
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“String.prototype.isWellFormed() - JavaScript | MDN” (MDN Web Docs). Retrieved January 25, 2024.
String.prototype.localeCompare()
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.
referenceStr occurs before compareStringreferenceStr occurs after compareString0 if they are equivalentWarning: 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).
“String.prototype.localeCompare() - JavaScript | MDN” (MDN Web Docs). Retrieved January 25, 2024.
String.prototype.match()
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.
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).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.
g flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included.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']
“String.prototype.match() - JavaScript | MDN” (MDN Web Docs). Retrieved January 27, 2024.
String.prototype.matchAll()
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.
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').regexp is a regex, then it must have the global (g) flag set, or a TypeError is thrown.Return value
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" ]“String.prototype.matchAll() - JavaScript | MDN” (MDN Web Docs). Retrieved January 27, 2024.
String.prototype.normalize()
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); // 2Syntax
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.“String.prototype.normalize() - JavaScript | MDN” (MDN Web Docs). Retrieved January 29, 2024.
String.prototype.padEnd()
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
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"
“String.prototype.padEnd() - JavaScript | MDN” (MDN Web Docs). Retrieved January 29, 2024.
String.prototype.padStart()
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"
“String.prototype.padStart() - JavaScript | MDN” (MDN Web Docs). Retrieved January 29, 2024.
String.raw()
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
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.“String.raw() - JavaScript | MDN” (MDN Web Docs). Retrieved January 29, 2024.
String.prototype.repeat()
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
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)“String.prototype.repeat() - JavaScript | MDN” (MDN Web Docs). Retrieved January 30, 2024.
String.prototype.replace()
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.
string, it will replace the substring matched by pattern. A number of special replacement patterns are supported; see specifying a string as the replacement or keep reading for more info.function, it will be invoked for every match and its return value is used as the replacement text. See Specifying a function as the replacement or keep reading for more info.replacement as string patterns
The replacement string can include the following special replacement patterns:
Pattern Inserts:
"$".$& Inserts 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 matchedreplacement 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.
“String.prototype.replace() - JavaScript | MDN” (MDN Web Docs). Retrieved January 30, 2024.
String.prototype.replaceAll()
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.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
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“String.prototype.replaceAll() - JavaScript | MDN” (MDN Web Docs). Retrieved January 30, 2024.
String.prototype.search()
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.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
-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
“String.prototype.search() - JavaScript | MDN” (MDN Web Docs). Retrieved January 31, 2024.
String.prototype.slice()
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
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):
indexStart >= str.length, an empty string is returned.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).indexStart is omitted, undefined, or cannot be converted to a number, it’s treated as 0.indexEnd is omitted, undefined, or cannot be converted to a number, or if indexEnd >= str.length, slice() extracts to the end of the string.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).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); // ""
“String.prototype.slice() - JavaScript | MDN” (MDN Web Docs). Retrieved January 31, 2024.
String.prototype.split()
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)
Parametersseparator - 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.
0, [] is returned.Return value
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));
// []“String.prototype.split() - JavaScript | MDN” (MDN Web Docs). Retrieved January 31, 2024.