String.prototype.replace() - JavaScript

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.

Try it
------

Syntax
------

```js
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.

* If it's a string, it will replace the substring matched by `pattern`. A number of special replacement patterns are supported; see the Specifying a string as the replacement section below.
* If it's a function, it will be invoked for every match and its return value is used as the replacement text. The arguments supplied to this function are described in the Specifying a function as the replacement section below.

### Return value

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

Description
-----------

This method does not mutate the string value it's called on. It returns a new string.

A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the `g` flag, or use `replaceAll()` instead.

If `pattern` is an object with a `Symbol.replace` method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replace()`. In this case the behavior of `replace()` is entirely encoded by the `@@replace` method — for example, any mention of "capturing groups" in the description below is actually functionality provided by `RegExp.prototype[@@replace]`.

If the `pattern` is an empty string, the replacement is prepended to the start of the string.

```js
"xxx".replace("", "\_"); // "\_xxx"
```

A regexp with the `g` flag is the only case where `replace()` replaces more than once. For more information about how regex properties (especially the sticky flag) interact with `replace()`, see `RegExp.prototype[@@replace]()`.

### Specifying a string as the replacement

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 `n`th (`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.

```js
"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
```

### Specifying a function as the replacement

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.

**Note:** The above-mentioned special replacement patterns do *not* apply for strings returned from the replacer function.

The function has the following signature:

```js
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 `n`th 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 - #$*%'`:

```js
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 - #$\*%
```

The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

Examples
--------

### Defining the regular expression in replace()

In the following example, the regular expression is defined in `replace()` and includes the ignore case flag.

```js
const str = "Twas the night before Xmas...";
const newstr = str.replace(/xmas/i, "Christmas");
console.log(newstr); // Twas the night before Christmas...
```

This logs `'Twas the night before Christmas...'`.

**Note:** See the regular expression guide for more explanations about regular expressions.

### Using the global and ignoreCase flags with replace()

Global replace can only be done with a regular expression. In the following example, the regular expression includes the global and ignore case flags which permits `replace()` to replace each occurrence of `'apples'` in the string with `'oranges'`.

```js
const re = /apples/gi;
const str = "Apples are round, and apples are juicy.";
const newstr = str.replace(re, "oranges");
console.log(newstr); // oranges are round, and oranges are juicy.
```

This logs `'oranges are round, and oranges are juicy'`.

### Switching words in a string

The following script switches the words in the string. For the replacement text, the script uses capturing groups and the `$1` and `$2` replacement patterns.

```js
const re = /(\w+)\s(\w+)/;
const str = "Maria Cruz";
const newstr = str.replace(re, "$2, $1");
console.log(newstr); // Cruz, Maria
```

This logs `'Cruz, Maria'`.

### Using an inline function that modifies the matched characters

In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.

The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.

```js
function styleHyphenFormat(propertyName) {
  function upperToHyphenLower(match, offset, string) {
    return (offset > 0 ? "-" : "") + match.toLowerCase();
  }
  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
```

Given `styleHyphenFormat('borderTop')`, this returns `'border-top'`.

Because we want to further transform the *result* of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the `toLowerCase()` method. If we had tried to do this using the match without a function, the `toLowerCase()` would have no effect.

```js
// Won't work
const newString = propertyName.replace(/[A-Z]/g, "-" + "$&".toLowerCase());
```

This is because `'$&'.toLowerCase()` would first be evaluated as a string literal (resulting in the same `'$&'`) before using the characters as a pattern.

### Replacing a Fahrenheit degree with its Celsius equivalent

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with `"F"`. The function returns the Celsius number ending with `"C"`. For example, if the input number is `"212F"`, the function returns `"100C"`. If the number is `"0F"`, the function returns `"-17.77777777777778C"`.

The regular expression `test` checks for any number that ends with `F`. The number of Fahrenheit degrees is accessible to the function through its second parameter, `p1`. The function sets the Celsius number based on the number of Fahrenheit degrees passed in a string to the `f2c()` function. `f2c()` then returns the Celsius number. This function approximates Perl's `s///e` flag.

```js
function f2c(x) {
  function convert(str, p1, offset, s) {
    return `${((p1 - 32) \* 5) / 9}C`;
  }
  const s = String(x);
  const test = /(-?\d+(?:\.\d\*)?)F\b/g;
  return s.replace(test, convert);
}
```

### Making a generic replacer

Suppose we want to create a replacer that appends the offset data to every matched string. Because the replacer function already receives the `offset` parameter, it will be trivial if the regex is statically known.

```js
"abcd".replace(/(bc)/, (match, p1, offset) => `${match} (${offset}) `);
// "abc (1) d"
```

However, this replacer would be hard to generalize if we want it to work with any regex pattern. The replacer is *variadic* — the number of arguments it receives depends on the number of capturing groups present. We can use rest parameters, but it would also collect `offset`, `string`, etc. into the array. The fact that `groups` may or may not be passed depending on the identity of the regex would also make it hard to generically know which argument corresponds to the `offset`.

```js
function addOffset(match, ...args) {
  const offset = args.at(-2);
  return `${match} (${offset}) `;
}

console.log("abcd".replace(/(bc)/, addOffset)); // "abc (1) d"
console.log("abcd".replace(/(?<group>bc)/, addOffset)); // "abc (abcd) d"
```

The `addOffset` example above doesn't work when the regex contains a named group, because in this case `args.at(-2)` would be the `string` instead of the `offset`.

Instead, you need to extract the last few arguments based on type, because `groups` is an object while `string` is a string.

```js
function addOffset(match, ...args) {
  const hasNamedGroups = typeof args.at(-1) === "object";
  const offset = hasNamedGroups ? args.at(-3) : args.at(-2);
  return `${match} (${offset}) `;
}

console.log("abcd".replace(/(bc)/, addOffset)); // "abc (1) d"
console.log("abcd".replace(/(?<group>bc)/, addOffset)); // "abc (1) d"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.replace |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.replace` in `core-js` with fixes and implementation of modern behavior like `Symbol.replace` support
* `String.prototype.replaceAll()`
* `String.prototype.match()`
* `RegExp.prototype.exec()`
* `RegExp.prototype.test()`
* `Symbol.replace`
* `RegExp.prototype[@@replace]()`


String.prototype.endsWith() - JavaScript

String.prototype.endsWith()
===========================

The **`endsWith()`** method of `String` values determines whether a string ends with the characters of this string, returning `true` or `false` as appropriate.

Try it
------

Syntax
------

```js
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.

Description
-----------

This method lets you determine whether or not a string ends with another string. This method is case-sensitive.

Examples
--------

### Using endsWith()

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.endswith |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.endsWith` in `core-js`
* `String.prototype.startsWith()`
* `String.prototype.includes()`
* `String.prototype.indexOf()`
* `String.prototype.lastIndexOf()`


String.prototype.link() - JavaScript

String.prototype.link()
=======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`link()`** method of `String` values creates a string that embeds this string in an `<a>` element (`<a href="...">str</a>`), to be used as a hypertext link to another URL.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as `document.createElement()` instead.

Syntax
------

```js
link(url)
```

### Parameters

`url`

Any string that specifies the `href` attribute of the `<a>` element; it should be a valid URL (relative or absolute), with any `&` characters escaped as `&`.

### Return value

A string beginning with an `<a href="url">` start tag (double quotes in `url` are replaced with `"`), then the text `str`, and then an `</a>` end tag.

Examples
--------

### Using link()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "MDN Web Docs";

document.body.innerHTML = contentString.link("https://developer.mozilla.org/");
```

This will create the following HTML:

```html
<a href="https://developer.mozilla.org/">MDN Web Docs</a>
```

Instead of using `link()` and creating HTML text directly, you should use DOM APIs such as `document.createElement()`. For example:

```js
const contentString = "MDN Web Docs";
const elem = document.createElement("a");
elem.href = "https://developer.mozilla.org/";
elem.innerText = contentString;
document.body.appendChild(elem);
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.link |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.link` in `core-js`
* HTML wrapper methods
* `<a>`


String.prototype.trimStart() - JavaScript

String.prototype.trimStart()
============================

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.

Try it
------

Syntax
------

```js
trimStart()

trimLeft()
```

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

### Aliasing

After `trim()` was standardized, engines also implemented the non-standard method `trimLeft`. However, for consistency with `padStart()`, when the method got standardized, its name was chosen as `trimStart`. For web compatibility reasons, `trimLeft` remains as an alias to `trimStart`, and they refer to the exact same function object. In some engines this means:

```js
String.prototype.trimLeft.name === "trimStart";
```

Examples
--------

### Using trimStart()

The following example trims whitespace from the start of `str`, but not from its end.

```js
let str = " foo ";

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

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.trimstart |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.trimStart` in `core-js`
* `String.prototype.trim()`
* `String.prototype.trimEnd()`


String.prototype.slice() - JavaScript

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.

Try it
------

Syntax
------

```js
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`):
```

              indexStart        indexEnd
                  ↓               ↓
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| T | h | e |   | m | i | r | r | o | r |

                  m   i   r   r
                 _______________
                      ↑
                    Result
```

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

### Using slice() to create a new string

The following example uses `slice()` to create a new string.

```js
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); // ""
```

### Using slice() with negative indexes

The following example uses `slice()` with negative indexes.

```js
const str = "The morning is upon us.";
str.slice(-3); // 'us.'
str.slice(-3, -1); // 'us'
str.slice(0, -1); // 'The morning is upon us'
str.slice(4, -1); // 'morning is upon us'
```

 This example counts backwards from the end of the string by `11` to find the
 start index and forwards from the start of the string by `16` to find the end
 index.

```js
console.log(str.slice(-11, 16)); // "is u"
```

 Here it counts forwards from the start by `11` to find the start index and
 backwards from the end by `7` to find the end index.

```js
console.log(str.slice(11, -7)); // " is u"
```

 These arguments count backwards from the end by `5` to find the start index
 and backwards from the end by `1` to find the end index.

```js
console.log(str.slice(-5, -1)); // "n us"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.slice |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `String.prototype.substr()`
* `String.prototype.substring()`
* `Array.prototype.slice()`


String.prototype.codePointAt() - JavaScript

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.

Try it
------

Syntax
------

```js
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.
Description
-----------

Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character in a string called `str` is `str.length - 1`.

Unicode code points range from `0` to `1114111` (`0x10FFFF`). In UTF-16, each string index is a code unit with value `0` – `65535`. Higher code points are represented by *a pair* of 16-bit surrogate pseudo-characters. Therefore, `codePointAt()` returns a code point that may span two string indices. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

Examples
--------

### Using codePointAt()

```js
"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
```

### Looping with codePointAt()

Because using string indices for looping causes the same code point to be visited twice (once for the leading surrogate, once for the trailing surrogate), and the second time `codePointAt()` returns *only* the trailing surrogate, it's better to avoid looping by index.

```js
const str = "\ud83d\udc0e\ud83d\udc71\u2764";

for (let i = 0; i < str.length; i++) {
  console.log(str.codePointAt(i).toString(16));
}
// '1f40e', 'dc0e', '1f471', 'dc71', '2764'
```

Instead, use a `for...of` statement or spread the string, both of which invoke the string's `@@iterator`, which iterates by code points. Then, use `codePointAt(0)` to get the code point of each element.

```js
for (const codePoint of str) {
  console.log(codePoint.codePointAt(0).toString(16));
}
// '1f40e', '1f471', '2764'

[...str].map((cp) => cp.codePointAt(0).toString(16));
// ['1f40e', '1f471', '2764']
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.codepointat |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.codePointAt` in `core-js`
* `String.fromCodePoint()`
* `String.fromCharCode()`
* `String.prototype.charCodeAt()`
* `String.prototype.charAt()`


String.prototype.localeCompare() - JavaScript

String.prototype.localeCompare()
================================

The **`localeCompare()`** method of `String` values returns a number indicating whether this string comes before, or after, or is the same as the given string in sort order. In implementations with `Intl.Collator` API support, this method simply calls `Intl.Collator`.

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an `Intl.Collator` object and use the function provided by its `compare()` method.

Try it
------

Syntax
------

```js
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.

In implementations without `Intl.Collator` support, this parameter is ignored and the host's locale is usually used.

`options` Optional

An object adjusting the output format. Corresponds to the `options` parameter of the `Intl.Collator()` constructor.

In implementations without `Intl.Collator` support, this parameter is ignored.

See the `Intl.Collator()` constructor for details on the `locales` and `options` parameters and how to use them.

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

Description
-----------

 Returns an integer indicating whether the `referenceStr` comes
 before, after or is equivalent to the `compareString`.

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

Examples
--------

### Using localeCompare()

```js
// The letter "a" is before "c" yielding a negative value
"a".localeCompare("c"); // -2 or -1 (or some other negative value)

// Alphabetically the word "check" comes after "against" yielding a positive value
"check".localeCompare("against"); // 2 or 1 (or some other positive value)

// "a" and "a" are equivalent yielding a neutral value of zero
"a".localeCompare("a"); // 0
```

### Sort an array

`localeCompare()` enables case-insensitive sorting for an array.

```js
const items = ["réservé", "Premier", "Cliché", "communiqué", "café", "Adieu"];
items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true }));
// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']
```

### Check browser support for extended arguments

 The `locales` and `options` arguments are
 not supported in all browsers yet.

 To check whether an implementation supports them, use the `"i"` argument (a
 requirement that illegal language tags are rejected) and look for a
 `RangeError` exception:

```js
function localeCompareSupportsLocales() {
  try {
    "foo".localeCompare("bar", "i");
  } catch (e) {
    return e.name === "RangeError";
  }
  return false;
}
```

### Using locales

 The results provided by `localeCompare()` vary between languages. In order
 to get the sort order of the language used in the user interface of your application,
 make sure to specify that language (and possibly some fallback languages) using the
 `locales` argument:

```js
console.log("ä".localeCompare("z", "de")); // a negative value: in German, ä sorts before z
console.log("ä".localeCompare("z", "sv")); // a positive value: in Swedish, ä sorts after z
```

### Using options

 The results provided by `localeCompare()` can be customized using the
 `options` argument:

```js
// in German, ä has a as the base letter
console.log("ä".localeCompare("a", "de", { sensitivity: "base" })); // 0

// in Swedish, ä and a are separate base letters
console.log("ä".localeCompare("a", "sv", { sensitivity: "base" })); // a positive value
```

### Numeric sorting

```js
// by default, "2" > "10"
console.log("2".localeCompare("10")); // 1

// numeric using options:
console.log("2".localeCompare("10", undefined, { numeric: true })); // -1

// numeric using locales tag:
console.log("2".localeCompare("10", "en-u-kn-true")); // -1
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.localecompare |
| ECMAScript Internationalization API Specification # sup-String.prototype.localeCompare |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Collator`


String.prototype.includes() - JavaScript

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.

Try it
------

Syntax
------

```js
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.

Description
-----------

This method lets you determine whether or not a string includes another string.

### Case-sensitivity

The `includes()` method is case sensitive. For example, the following expression returns `false`:

```js
"Blue Whale".includes("blue"); // returns false
```

You can work around this constraint by transforming both the original string and the search string to all lowercase:

```js
"Blue Whale".toLowerCase().includes("blue"); // returns true
```

Examples
--------

### Using includes()

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.includes |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.includes` in `core-js`
* `Array.prototype.includes()`
* `TypedArray.prototype.includes()`
* `String.prototype.indexOf()`
* `String.prototype.lastIndexOf()`
* `String.prototype.startsWith()`
* `String.prototype.endsWith()`


String.prototype.replaceAll() - JavaScript

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.

Try it
------

Syntax
------

```js
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"`).

Description
-----------

This method does not mutate the string value it's called on. It returns a new string.

Unlike `replace()`, this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the `RegExp()` constructor without escaping special characters may unintentionally change its semantics.

```js
function unsafeRedactName(text, name) {
  return text.replace(new RegExp(name, "g"), "[REDACTED]");
}
function safeRedactName(text, name) {
  return text.replaceAll(name, "[REDACTED]");
}

const report =
  "A hacker called ha.\*er used special characters in their name to breach the system.";

console.log(unsafeRedactName(report, "ha.\*er")); // "A [REDACTED]s in their name to breach the system."
console.log(safeRedactName(report, "ha.\*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system."
```

If `pattern` is an object with a `Symbol.replace` method (including `RegExp` objects), that method is called with the target string and `replacement` as arguments. Its return value becomes the return value of `replaceAll()`. In this case the behavior of `replaceAll()` is entirely encoded by the `@@replace` method, and therefore will have the same result as `replace()` (apart from the extra input validation that the regex is global).

If the `pattern` is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to `split()` behavior.

```js
"xxx".replaceAll("", "\_"); // "\_x\_x\_x\_"
```

For more information about how regex properties (especially the sticky flag) interact with `replaceAll()`, see `RegExp.prototype[@@replace]()`.

Examples
--------

### Using replaceAll()

```js
"aabbcc".replaceAll("b", ".");
// 'aa..cc'
```

### Non-global regex throws

When using a regular expression search value, it must be global. This won't work:

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

This will work:

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.replaceall |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.replaceAll` in `core-js`
* `String.prototype.replace()`
* `String.prototype.match()`
* `RegExp.prototype.exec()`
* `RegExp.prototype.test()`


String.prototype.toUpperCase() - JavaScript

String.prototype.toUpperCase()
==============================

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

Try it
------

Syntax
------

```js
toUpperCase()
```

### Parameters

None.

### Return value

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

Description
-----------

 The `toUpperCase()` method returns the value of the string converted to
 uppercase. This method does not affect the value of the string itself since JavaScript
 strings are immutable.

Examples
--------

### Basic usage

```js
console.log("alphabet".toUpperCase()); // 'ALPHABET'
```

### Conversion of non-string `this` values to strings

 This method will convert any non-string value to a string, when you set its
 `this` to a value that is not a string:

```js
const a = String.prototype.toUpperCase.call({
  toString() {
    return "abcdef";
  },
});

const b = String.prototype.toUpperCase.call(true);

// prints out 'ABCDEF TRUE'.
console.log(a, b);
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.touppercase |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `String.prototype.toLocaleLowerCase()`
* `String.prototype.toLocaleUpperCase()`
* `String.prototype.toLowerCase()`


String.prototype.valueOf() - JavaScript

String.prototype.valueOf()
==========================

The **`valueOf()`** method of `String` values returns this string value.

Try it
------

Syntax
------

```js
valueOf()
```

### Parameters

None.

### Return value

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

Description
-----------

 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.

Examples
--------

### Using `valueOf()`

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.valueof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `String.prototype.toString()`
* `Object.prototype.valueOf()`


String.prototype.sub() - JavaScript

String.prototype.sub()
======================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`sub()`** method of `String` values creates a string that embeds this string in a `<sub>` element (`<sub>str</sub>`), which causes this string to be displayed as subscript.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as `document.createElement()` instead.

Syntax
------

```js
sub()
```

### Parameters

None.

### Return value

A string beginning with a `<sub>` start tag, then the text `str`, and then a `</sub>` end tag.

Examples
--------

### Using sub()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.sub();
```

This will create the following HTML:

```html
<sub>Hello, world</sub>
```

Instead of using `sub()` and creating HTML text directly, you should use DOM APIs such as `document.createElement()`. For example:

```js
const contentString = "Hello, world";
const elem = document.createElement("sub");
elem.innerText = contentString;
document.body.appendChild(elem);
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.sub |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.sub` in `core-js`
* HTML wrapper methods
* `<sub>`


String.prototype.fontcolor() - JavaScript

String.prototype.fontcolor()
============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`fontcolor()`** method of `String` values creates a string that embeds this string in a `<font>` element (`<font color="...">str</font>`), which causes this string to be displayed in the specified font color.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of `fontcolor()`, the `<font>` element itself has been removed from the HTML specification and shouldn't be used anymore. Web developers should use CSS properties instead.

Syntax
------

```js
fontcolor(color)
```

### Parameters

`color`

A string expressing the color as a hexadecimal RGB triplet or as a string literal. String literals for color names are listed in the CSS color reference.

### Return value

A string beginning with a `<font color="color">` start tag (double quotes in `color` are replaced with `"`), then the text `str`, and then a `</font>` end tag.

Description
-----------

The `fontcolor()` method itself simply joins the string parts together without any validation or normalization. However, to create valid `<font>` elements, if you express color as a hexadecimal RGB triplet, you must use the format `rrggbb`. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is `"FA8072"`.

Examples
--------

### Using fontcolor()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.fontcolor("red");
```

This will create the following HTML:

```html
<font color="red">Hello, world</font>
```

**Warning:** This markup is invalid, because `font` is no longer a valid element.

Instead of using `fontcolor()` and creating HTML text directly, you should use CSS to manipulate fonts. For example, you can manipulate `color` through the `element.style` attribute:

```js
document.getElementById("yourElemId").style.color = "red";
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.fontcolor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.fontcolor` in `core-js`
* HTML wrapper methods
* `<font>`


String.fromCharCode() - JavaScript

String.fromCharCode()
=====================

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

Try it
------

Syntax
------

```js
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.

Description
-----------

Because `fromCharCode()` is a static method of `String`, you always use it as `String.fromCharCode()`, rather than as a method of a `String` value you created.

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.

Because `fromCharCode()` only works with 16-bit values (same as the `\u` escape sequence), a surrogate pair is required in order to return a supplementary character. For example, both `String.fromCharCode(0xd83c, 0xdf03)` and `"\ud83c\udf03"` return code point `U+1F303` "Night with Stars". While there is a mathematical relationship between the supplementary code point value (e.g. `0x1f303`) and both surrogate values that represent it (e.g., `0xd83c` and `0xdf03`), it does require an extra step to either calculate or look up the surrogate pair values every time a supplementary code point is to be used. For this reason, it's more convenient to use `String.fromCodePoint()`, which allows for returning supplementary characters based on their actual code point value. For example, `String.fromCodePoint(0x1f303)` returns code point `U+1F303` "Night with Stars".

Examples
--------

### Using fromCharCode()

BMP characters, in UTF-16, use a single code unit:

```js
String.fromCharCode(65, 66, 67); // returns "ABC"
String.fromCharCode(0x2014); // returns "—"
String.fromCharCode(0x12014); // also returns "—"; the digit 1 is truncated and ignored
String.fromCharCode(8212); // also returns "—"; 8212 is the decimal form of 0x2014
```

Supplementary characters, in UTF-16, require two code units (i.e. a surrogate pair):

```js
String.fromCharCode(0xd83c, 0xdf03); // Code Point U+1F303 "Night with
String.fromCharCode(55356, 57091); // Stars" === "\uD83C\uDF03"

String.fromCharCode(0xd834, 0xdf06, 0x61, 0xd834, 0xdf07); // "\uD834\uDF06a\uD834\uDF07"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.fromcharcode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `String.fromCodePoint()`
* `String.prototype.charAt()`
* `String.prototype.charCodeAt()`
* `String.prototype.codePointAt()`


String.raw() - JavaScript

String.raw()
============

The **`String.raw()`** static method is a tag function of template literals. This is similar to the `r` prefix in Python, or the `@` prefix in C# for string 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.

Try it
------

Syntax
------

```js
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`.

Description
-----------

In most cases, `String.raw()` is used with template literals. The first syntax mentioned above is only rarely used, because the JavaScript engine will call this with proper arguments for you, (just like with other tag functions).

`String.raw()` is the only built-in template literal tag. It has close semantics to an untagged literal since it concatenates all arguments and returns a string. You can even re-implement it with normal JavaScript code.

**Warning:** You should not use `String.raw` directly as an "identity" tag. See Building an identity tag for how to implement this.

If `String.raw()` is called with an object whose `raw` property doesn't have a `length` property or a non-positive `length`, it returns an empty string `""`. If `substitutions.length < strings.raw.length - 1` (i.e. there are not enough substitutions to fill the placeholders — which can't happen in a well-formed tagged template literal), the rest of the placeholders are filled with empty strings.

Examples
--------

### Using String.raw()

```js
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.
```

### Building an identity tag

Many tools give special treatment to literals tagged by a particular name.

```js
// Some formatters will format this literal's content as HTML
const doc = html`<!DOCTYPE html>
<html lang="en-US">
 <head>
 <title>Hello</title>
 </head>
 <body>
 <h1>Hello world!</h1>
 </body>
</html>
`;
```

One might naïvely implement the `html` tag as:

```js
const html = String.raw;
```

This, in fact, works for the case above. However, because `String.raw` would concatenate the *raw* string literals instead of the "cooked" ones, escape sequences would not be processed.

```js
const doc = html`<canvas>\n</canvas>`;
// "<canvas>\\n</canvas>"
```

This may not be what you want for a "true identity" tag, where the tag is purely for markup and doesn't change the literal's value. In this case, you can create a custom tag and pass the "cooked" (i.e. escape sequences are processed) literal array to `String.raw`, pretending they are raw strings.

```js
const html = (strings, ...values) => String.raw({ raw: strings }, ...values);
// Some formatters will format this literal's content as HTML
const doc = html`<canvas>\n</canvas>`;
// "<canvas>\n</canvas>"; the "\n" becomes a line break
```

Notice the first argument is an object with a `raw` property, whose value is an array-like object (with a `length` property and integer indexes) representing the separated strings in the template literal. The rest of the arguments are the substitutions. Since the `raw` value can be any array-like object, it can even be a string! For example, `'test'` is treated as `['t', 'e', 's', 't']`. The following is equivalent to ``t${0}e${1}s${2}t``:

```js
String.raw({ raw: "test" }, 0, 1, 2); // 't0e1s2t'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.raw |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.raw` in `core-js`
* Template literals
* `String`
* Lexical grammar


String.prototype.anchor() - JavaScript

String.prototype.anchor()
=========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`anchor()`** method of `String` values creates a string that embeds this string in an `<a>` element with a name (`<a name="...">str</a>`).

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as `document.createElement()` instead.

The HTML specification no longer allows the `<a>` element to have a `name` attribute, so this method doesn't even create valid markup.

Syntax
------

```js
anchor(name)
```

### Parameters

`name`

A string representing a `name` value to put into the generated `<a name="...">` start tag.

### Return value

A string beginning with an `<a name="name">` start tag (double quotes in `name` are replaced with `"`), then the text `str`, and then an `</a>` end tag.

Examples
--------

### Using anchor()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.anchor("hello");
```

This will create the following HTML:

```html
<a name="hello">Hello, world</a>
```

**Warning:** This markup is invalid, because `name` is no longer a valid attribute of the `<a>` element.

Instead of using `anchor()` and creating HTML text directly, you should use DOM APIs such as `document.createElement()`. For example:

```js
const contentString = "Hello, world";
const elem = document.createElement("a");
elem.innerText = contentString;
document.body.appendChild(elem);
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.anchor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.anchor` in `core-js`
* HTML wrapper methods
* `<a>`


String.prototype.substring() - JavaScript

String.prototype.substring()
============================

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.

Try it
------

Syntax
------

```js
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; see example below.

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

### Using substring()

 The following example uses `substring()` to display characters from the
 string `"Mozilla"`:

```js
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"
```

### Using substring() with length property

 The following example uses the `substring()` method and
 `length` property to extract the last characters of a
 particular string. This method may be easier to remember, given that you don't need to
 know the starting and ending indices as you would in the above examples.

```js
const text = "Mozilla";

// Takes 4 last characters of string
console.log(text.substring(text.length - 4)); // prints "illa"

// Takes 5 last characters of string
console.log(text.substring(text.length - 5)); // prints "zilla"
```

### The difference between substring() and substr()

 There are subtle differences between the `substring()` and
 `substr()` methods, so you should be careful not to get
 them confused.

* The two parameters of `substr()` are `start` and `length`, while for `substring()`, they are `start` and `end`.
* `substr()`'s `start` index will wrap to the end of the string if it is negative, while `substring()` will clamp it to `0`.
* Negative lengths in `substr()` are treated as zero, while `substring()` will swap the two indexes if `end` is less than `start`.

Furthermore, `substr()` is considered a *legacy feature in ECMAScript*, so it is best to avoid using it if possible.

```js
const text = "Mozilla";
console.log(text.substring(2, 5)); // "zil"
console.log(text.substr(2, 3)); // "zil"
```

### Differences between substring() and slice()

 The `substring()` and `slice()` methods are
 almost identical, but there are a couple of subtle differences between the two,
 especially in the way negative arguments are dealt with.

 The `substring()` method swaps its two arguments if
 `indexStart` is greater than `indexEnd`,
 meaning that a string is still returned. The `slice()`
 method returns an empty string if this is the case.

```js
const text = "Mozilla";
console.log(text.substring(5, 2)); // "zil"
console.log(text.slice(5, 2)); // ""
```

 If either or both of the arguments are negative or `NaN`, the
 `substring()` method treats them as if they were `0`.

```js
console.log(text.substring(-5, 2)); // "Mo"
console.log(text.substring(-5, -2)); // ""
```

`slice()` also treats `NaN` arguments as `0`, but when
 it is given negative values it counts backwards from the end of the string to find the
 indexes.

```js
console.log(text.slice(-5, 2)); // ""
console.log(text.slice(-5, -2)); // "zil"
```

 See the `slice()` page for more examples with negative
 numbers.

### Replacing a substring within a string

 The following example replaces a substring within a string. It will replace both
 individual characters and substrings. The function call at the end of the example
 changes the string `Brave New World` to `Brave New Web`.

```js
// Replaces oldS with newS in the string fullS
function replaceString(oldS, newS, fullS) {
  for (let i = 0; i < fullS.length; ++i) {
    if (fullS.substring(i, i + oldS.length) === oldS) {
      fullS =
        fullS.substring(0, i) +
        newS +
        fullS.substring(i + oldS.length, fullS.length);
    }
  }
  return fullS;
}

replaceString("World", "Web", "Brave New World");
```

 Note that this can result in an infinite loop if `oldS` is itself a
 substring of `newS` — for example, if you attempted to replace
 `"World"` with `"OtherWorld"` here.

A better method for replacing strings is as follows:

```js
function replaceString(oldS, newS, fullS) {
  return fullS.split(oldS).join(newS);
}
```

 The code above serves as an example for substring operations. If you need to replace
 substrings, most of the time you will want to use
 `String.prototype.replace()`.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.substring |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `String.prototype.substr()`
* `String.prototype.slice()`


String.prototype.at() - JavaScript

String.prototype.at()
=====================

The **`at()`** method of `String` values takes an integer value and returns a new `String` consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character.

Try it
------

Syntax
------

```js
at(index)
```

### Parameters

`index`

The index (position) of the string character to be returned. Supports relative indexing from the end of the string when passed a negative index; i.e. if a negative number is used, the character returned will be found by counting back from the end of the string.

### Return value

A `String` consisting of the single UTF-16 code unit located at the specified position. Returns `undefined` if the given index can not be found.

Examples
--------

### Return the last character of a string

The following example provides a function which returns the last character found in a specified string.

```js
// A function which returns the last character of a given string
function returnLast(arr) {
  return arr.at(-1);
}

let invoiceRef = "myinvoice01";

console.log(returnLast(invoiceRef)); // '1'

invoiceRef = "myinvoice02";

console.log(returnLast(invoiceRef)); // '2'
```

### Comparing methods

Here we compare different ways to select the penultimate (last but one) character of a `String`. Whilst all below methods are valid, it highlights the succinctness and readability of the `at()` method.

```js
const myString = "Every green bus drives fast.";

// Using length property and charAt() method
const lengthWay = myString.charAt(myString.length - 2);
console.log(lengthWay); // 't'

// Using slice() method
const sliceWay = myString.slice(-2, -1);
console.log(sliceWay); // 't'

// Using at() method
const atWay = myString.at(-2);
console.log(atWay); // 't'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.at |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.at` in `core-js`
* `String.prototype.indexOf()`
* `String.prototype.lastIndexOf()`
* `String.prototype.charCodeAt()`
* `String.prototype.codePointAt()`
* `String.prototype.split()`


String.prototype.trim() - JavaScript

String.prototype.trim()
=======================

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

Try it
------

Syntax
------

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

### Using trim()

The following example trims whitespace from both ends of `str`.

```js
const str = " foo ";
console.log(str.trim()); // 'foo'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.trim |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `String.prototype.trimStart()`
* `String.prototype.trimEnd()`


String.prototype.search() - JavaScript

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.

Try it
------

Syntax
------

```js
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.

Description
-----------

The implementation of `String.prototype.search()` itself is very simple — it simply calls the `Symbol.search` method of the argument with the string as the first parameter. The actual implementation comes from `RegExp.prototype[@@search]()`.

The `g` flag of `regexp` has no effect on the `search()` result, and the search always happens as if the regex's `lastIndex` is 0. For more information on the behavior of `search()`, see `RegExp.prototype[@@search]()`.

When you want to know whether a pattern is found, and *also* know its index within a string, use `search()`.

* If you only want to know if it exists, use the `RegExp.prototype.test()` method, which returns a boolean.
* If you need the content of the matched text, use `String.prototype.match()` or `RegExp.prototype.exec()`.
Examples
--------

### Using search()

The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (`-1`).

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.search |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.search` in `core-js` with fixes and implementation of modern behavior like `Symbol.search` support
* Regular expressions guide
* `String.prototype.match()`
* `RegExp.prototype.exec()`
* `RegExp.prototype[@@search]()`


String.prototype.toLocaleLowerCase() - JavaScript

String.prototype.toLocaleLowerCase()
====================================

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

Try it
------

Syntax
------

```js
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. 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, `toLocaleLowerCase()` does not allow locale matching. Therefore, after checking the validity of the `locales` argument, `toLocaleLowerCase()` 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 lower case, according to any
 locale-specific case mappings.

Description
-----------

 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.

Examples
--------

### Using toLocaleLowerCase()

```js
"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
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.tolocalelowercase |
| ECMAScript Internationalization API Specification # sup-string.prototype.tolocalelowercase |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `String.prototype.toLocaleUpperCase()`
* `String.prototype.toLowerCase()`
* `String.prototype.toUpperCase()`


String: length - JavaScript

String: length
==============

The **`length`** data property of a `String` value contains the length of the string in UTF-16 code units.

Try it
------

Value
-----

A non-negative integer.

| Property attributes of `String: length` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Description
-----------

This property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by `length` to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, mathematical symbols, or obscure Chinese characters, you may need to account for the difference between code units and characters.

The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for precise integers. However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer.

* In V8 (used by Chrome and Node), the maximum length is 229 - 24 (~1GiB). On 32-bit systems, the maximum length is 228 - 16 (~512MiB).
* In Firefox, the maximum length is 230 - 2 (~2GiB). Before Firefox 65, the maximum length was 228 - 1 (~512MiB).
* In Safari, the maximum length is 231 - 1 (~4GiB).

For an empty string, `length` is 0.

The static property `String.length` is unrelated to the length of strings. It's the arity of the `String` function (loosely, the number of formal parameters it has), which is 1.

Since `length` counts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:

```js
function getCharacterLength(str) {
  // The string iterator that is used here iterates over characters,
  // not mere code units
  return [...str].length;
}

console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3
```

Examples
--------

### Basic usage

```js
const x = "Mozilla";
const empty = "";

console.log(`${x} is ${x.length} code units long`);
// Mozilla is 7 code units long

console.log(`The empty string has a length of ${empty.length}`);
// The empty string has a length of 0
```

### Strings with length not equal to the number of characters

```js
const emoji = "😄";
console.log(emoji.length); // 2
console.log([...emoji].length); // 1
const adlam = "𞤲𞥋𞤣𞤫";
console.log(adlam.length); // 8
console.log([...adlam].length); // 4
const formula = "∀𝑥∈ℝ,𝑥²≥0";
console.log(formula.length); // 11
console.log([...formula].length); // 9
```

### Assigning to length

Because string is a primitive, attempting to assign a value to a string's `length` property has no observable effect, and will throw in strict mode.

```js
const myString = "bluebells";

myString.length = 4;
console.log(myString); // "bluebells"
console.log(myString.length); // 9
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-properties-of-string-instances-length |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Array`: `length`


String.prototype.trimEnd() - JavaScript

String.prototype.trimEnd()
==========================

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.

Try it
------

Syntax
------

```js
trimEnd()

trimRight()
```

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

### Aliasing

After `trim()` was standardized, engines also implemented the non-standard method `trimRight`. However, for consistency with `padEnd()`, when the method got standardized, its name was chosen as `trimEnd`. For web compatibility reasons, `trimRight` remains as an alias to `trimEnd`, and they refer to the exact same function object. In some engines this means:

```js
String.prototype.trimRight.name === "trimEnd";
```

Examples
--------

### Using trimEnd()

The following example trims whitespace from the end of `str`, but not from its start.

```js
let str = " foo ";

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

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.trimend |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.trimEnd` in `core-js`
* `String.prototype.trim()`
* `String.prototype.trimStart()`


String.prototype.charCodeAt() - JavaScript

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

Try it
------

Syntax
------

```js
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`.

Description
-----------

Characters in a string are indexed from left to right. The index of the first character is `0`, and the index of the last character in a string called `str` is `str.length - 1`.

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 get a full character with value greater than `65535`, it is necessary to retrieve not only `charCodeAt(i)`, but also `charCodeAt(i + 1)` (as if manipulating a string with two characters), or to use `codePointAt(i)` instead. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.

Examples
--------

### Using charCodeAt()

The following example returns `65`, the Unicode value for A.

```js
"ABC".charCodeAt(0); // returns 65
```

`charCodeAt()` may return lone surrogates, which are not valid Unicode characters.

```js
const str = "𠮷𠮾";
console.log(str.charCodeAt(0)); // 55362, or d842, which is not a valid Unicode character
console.log(str.charCodeAt(1)); // 57271, or dfb7, which is not a valid Unicode character
```

To get the full Unicode code point at the given index, use `String.prototype.codePointAt()`.

```js
const str = "𠮷𠮾";
console.log(str.codePointAt(0)); // 134071
```

**Note:** Avoid re-implementing `codePointAt()` using `charCodeAt()`. The translation from UTF-16 surrogates to Unicode code points is complex, and `codePointAt()` may be more performant as it directly uses the internal representation of the string. Install a polyfill for `codePointAt()` if necessary.

Below is a possible algorithm to convert a pair of UTF-16 code units into a Unicode code point, adapted from the Unicode FAQ:

```js
// constants
const LEAD\_OFFSET = 0xd800 - (0x10000 >> 10);
const SURROGATE\_OFFSET = 0x10000 - (0xd800 << 10) - 0xdc00;

function utf16ToUnicode(lead, trail) {
  return (lead << 10) + trail + SURROGATE\_OFFSET;
}
function unicodeToUTF16(codePoint) {
  const lead = LEAD\_OFFSET + (codePoint >> 10);
  const trail = 0xdc00 + (codePoint & 0x3ff);
  return [lead, trail];
}

const str = "𠮷";
console.log(utf16ToUnicode(str.charCodeAt(0), str.charCodeAt(1))); // 134071
console.log(str.codePointAt(0)); // 134071
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.charcodeat |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `String.fromCharCode()`
* `String.prototype.charAt()`
* `String.fromCodePoint()`
* `String.prototype.codePointAt()`


String.prototype.startsWith() - JavaScript

String.prototype.startsWith()
=============================

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

Try it
------

Syntax
------

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

`TypeError`

Thrown if `searchString` is a regex.

Description
-----------

This method lets you determine whether or not a string begins with another string. This method is case-sensitive.

Examples
--------

### Using startsWith()

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.startswith |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.startsWith` in `core-js`
* `String.prototype.endsWith()`
* `String.prototype.includes()`
* `String.prototype.indexOf()`
* `String.prototype.lastIndexOf()`


String.prototype.blink() - JavaScript

String.prototype.blink()
========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`blink()`** method of `String` values creates a string that embeds this string in a `<blink>` element (`<blink>str</blink>`), which used to cause a string to blink in old browsers.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. For the case of `blink()`, the `<blink>` element itself is removed from modern browsers, and blinking text is frowned upon by several accessibility standards. Avoid using the element in any way.

Syntax
------

```js
blink()
```

### Parameters

None.

### Return value

A string beginning with a `<blink>` start tag, then the text `str`, and then a `</blink>` end tag.

Examples
--------

### Using blink()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.blink();
```

This will create the following HTML:

```html
<blink>Hello, world</blink>
```

**Warning:** This markup is invalid, because `blink` is no longer a valid element.

You should avoid blinking elements altogether.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.blink |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.blink` in `core-js`
* HTML wrapper methods


String.prototype.normalize() - JavaScript

String.prototype.normalize()
============================

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

Try it
------

Syntax
------

```js
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.

Description
-----------

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

```js
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.

```js
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**.

### Canonical equivalence normalization

 In Unicode, two sequences of code points have canonical equivalence if they represent
 the same abstract characters, and should always have the same visual appearance and
 behavior (for example, they should always be sorted in the same way).

 You can use `normalize()` using the `"NFD"` or `"NFC"`
 arguments to produce a form of the string that will be the same for all canonically
 equivalent strings. In the example below we normalize two representations of the
 character `"ñ"`:

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

#### Composed and decomposed forms

 Note that the length of the normalized form under `"NFD"` is
 `2`. That's because `"NFD"` gives you the
 **decomposed** version of the canonical form, in which single code points
 are split into multiple combining ones. The decomposed canonical form for
 `"ñ"` is `"\u006E\u0303"`.

 You can specify `"NFC"` to get the **composed** canonical form,
 in which multiple code points are replaced with single code points where possible. The
 composed canonical form for `"ñ"` is `"\u00F1"`:

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

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

console.log(string1 === string2); // true
console.log(string1.length); // 1
console.log(string2.length); // 1
console.log(string2.codePointAt(0).toString(16)); // f1
```

### Compatibility normalization

 In Unicode, two sequences of code points are compatible if they represent the same
 abstract characters, and should be treated alike in some — but not necessarily all —
 applications.

All canonically equivalent sequences are also compatible, but not vice versa.

For example:

* the code point U+FB00 represents the ligature `"ﬀ"`. It is compatible
 with two consecutive U+0066 code points (`"ff"`).
* the code point U+24B9 represents the symbol
 `"Ⓓ"`.
 It is compatible with the U+0044 code point (`"D"`).

 In some respects (such as sorting) they should be treated as equivalent—and in some
 (such as visual appearance) they should not, so they are not canonically equivalent.

 You can use `normalize()` using the `"NFKD"` or
 `"NFKC"` arguments to produce a form of the string that will be the same for
 all compatible strings:

```js
let string1 = "\uFB00";
let string2 = "\u0066\u0066";

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

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

console.log(string1); // ff <- visual appearance changed
console.log(string2); // ff
console.log(string1 === string2); // true
console.log(string1.length); // 2
console.log(string2.length); // 2
```

 When applying compatibility normalization it's important to consider what you intend to
 do with the strings, since the normalized form may not be appropriate for all
 applications. In the example above the normalization is appropriate for search, because
 it enables a user to find the string by searching for `"f"`. But it may not
 be appropriate for display, because the visual representation is different.

 As with canonical normalization, you can ask for decomposed or composed compatible
 forms by passing `"NFKD"` or `"NFKC"`, respectively.

Examples
--------

### Using normalize()

```js
// Initial string

// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
// U+0323: COMBINING DOT BELOW
const str = "\u1E9B\u0323";

// Canonically-composed form (NFC)

// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
// U+0323: COMBINING DOT BELOW
str.normalize("NFC"); // '\u1E9B\u0323'
str.normalize(); // same as above

// Canonically-decomposed form (NFD)

// U+017F: LATIN SMALL LETTER LONG S
// U+0323: COMBINING DOT BELOW
// U+0307: COMBINING DOT ABOVE
str.normalize("NFD"); // '\u017F\u0323\u0307'

// Compatibly-composed (NFKC)

// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
str.normalize("NFKC"); // '\u1E69'

// Compatibly-decomposed (NFKD)

// U+0073: LATIN SMALL LETTER S
// U+0323: COMBINING DOT BELOW
// U+0307: COMBINING DOT ABOVE
str.normalize("NFKD"); // '\u0073\u0323\u0307'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.normalize |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Unicode Standard Annex #15, Unicode Normalization Forms
* Unicode equivalence on Wikipedia


String.prototype.toWellFormed() - JavaScript

String.prototype.toWellFormed()
===============================

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

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

Description
-----------

Strings in JavaScript are UTF-16 encoded. UTF-16 encoding has the concept of *surrogate pairs*, which is introduced in detail in the UTF-16 characters, Unicode code points, and grapheme clusters section.

`toWellFormed()` iterates through the code units of this string, and replaces any lone surrogates with the Unicode replacement character U+FFFD `�`. This ensures that the returned string is well-formed and can be used in functions that expect well-formed strings, such as `encodeURI`. Compared to a custom implementation, `toWellFormed()` is more efficient, as engines can directly access the internal representation of strings.

When ill-formed strings are used in certain contexts, such as `TextEncoder`, they are automatically converted to well-formed strings using the same replacement character. When lone surrogates are rendered, they are also rendered as the replacement character (a diamond with a question mark inside).

Examples
--------

### Using toWellFormed()

```js
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"
```

### Avoiding errors in encodeURI()

`encodeURI` throws an error if the string passed is not well-formed. This can be avoided by using `toWellFormed()` to convert the string to a well-formed string first.

```js
const illFormed = "https://example.com/search?q=\uD800";

try {
  encodeURI(illFormed);
} catch (e) {
  console.log(e); // URIError: URI malformed
}

console.log(encodeURI(illFormed.toWellFormed())); // "https://example.com/search?q=%EF%BF%BD"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.towellformed |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.toWellFormed` in `core-js`
* `String.prototype.isWellFormed()`
* `String.prototype.normalize()`


String.prototype[@@iterator]() - JavaScript

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.

Try it
------

Syntax
------

```js
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.

Description
-----------

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

```js
// "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
```

Examples
--------

### Iteration using for...of loop

Note that 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.

```js
const str = "A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A";

for (const v of str) {
  console.log(v);
}
// "A"
// "\uD835\uDC68"
// "B"
// "\uD835\uDC69"
// "C"
// "\uD835\uDC6A"
```

### Manually hand-rolling the iterator

You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.

```js
const str = "A\uD835\uDC68";

const strIter = str[Symbol.iterator]();

console.log(strIter.next().value); // "A"
console.log(strIter.next().value); // "\uD835\uDC68"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype-@@iterator |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype[@@iterator]` in `core-js`
* Text formatting guide
* `Symbol.iterator`
* Iteration protocols


String.prototype.padStart() - JavaScript

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.

Try it
------

Syntax
------

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

### Basic examples

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

### Fixed width string number conversion

```js
// JavaScript version of: (unsigned)
// printf "%0\*d" width num
function leftFillNum(num, targetLength) {
  return num.toString().padStart(targetLength, "0");
}

const num = 123;
console.log(leftFillNum(num, 5)); // "00123"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.padstart |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.padStart` in `core-js`
* `String.prototype.padEnd()`


String.prototype.small() - JavaScript

String.prototype.small()
========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`small()`** method of `String` values creates a string that embeds this string in a `<small>` element (`<small>str</small>`), which causes this string to be displayed in a small font.

**Note:** All HTML wrapper methods are deprecated and only standardized for compatibility purposes. Use DOM APIs such as `document.createElement()` instead.

Syntax
------

```js
small()
```

### Parameters

None.

### Return value

A string beginning with a `<small>` start tag, then the text `str`, and then a `</small>` end tag.

Examples
--------

### Using small()

The code below creates an HTML string and then replaces the document's body with it:

```js
const contentString = "Hello, world";

document.body.innerHTML = contentString.small();
```

This will create the following HTML:

```html
<small>Hello, world</small>
```

Instead of using `small()` and creating HTML text directly, you should use DOM APIs such as `document.createElement()`. For example:

```js
const contentString = "Hello, world";
const elem = document.createElement("small");
elem.innerText = contentString;
document.body.appendChild(elem);
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.small |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.small` in `core-js`
* HTML wrapper methods
* `<small>`


String.prototype.padEnd() - JavaScript

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.

Try it
------

Syntax
------

```js
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 " "
 (`U+0020`).

### Return value

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

Examples
--------

### Using padEnd

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

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-string.prototype.padend |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `String.prototype.padEnd` in `core-js`
* `String.prototype.padStart()`