JavaScript String toWellFormed()
Syntax & Examples
String.toWellFormed() method
The toWellFormed() method of the String class in JavaScript returns a string where all lone surrogates of the original string are replaced with the Unicode replacement character U+FFFD.
Syntax of String.toWellFormed()
The syntax of String.toWellFormed() method is:
toWellFormed()
This toWellFormed() method of String returns a string where all lone surrogates of this string are replaced with the Unicode replacement character U+FFFD.
Return Type
String.toWellFormed() returns value of type String
.
✐ Examples
1 Using toWellFormed() method to replace lone surrogates
In JavaScript, the toWellFormed()
method replaces lone surrogates with the Unicode replacement character U+FFFD.
For example,
- We define a string variable
str
containing a lone surrogate'\uD800'
. - We use the
toWellFormed()
method to replace the lone surrogate with U+FFFD. - The result is stored in the variable
wellFormedStr
. - We log
wellFormedStr
to the console using theconsole.log()
method.
JavaScript Program
const str = '\uD800';
const wellFormedStr = str.toWellFormed();
console.log(wellFormedStr);
Output
�
2 Using toWellFormed() method on a string with multiple lone surrogates
In JavaScript, the toWellFormed()
method can replace multiple lone surrogates in a string.
For example,
- We define a string variable
str
containing multiple lone surrogates'\uD800\uDC00\uD800'
. - We use the
toWellFormed()
method to replace the lone surrogates with U+FFFD. - The result is stored in the variable
wellFormedStr
. - We log
wellFormedStr
to the console using theconsole.log()
method.
JavaScript Program
const str = '\uD800\uDC00\uD800';
const wellFormedStr = str.toWellFormed();
console.log(wellFormedStr);
Output
���
3 Using toWellFormed() method on a well-formed string
In JavaScript, the toWellFormed()
method does not alter a string that is already well-formed.
For example,
- We define a string variable
str
containing a well-formed Unicode string'Hello \uD83D\uDE00'
. - We use the
toWellFormed()
method. - The result is stored in the variable
wellFormedStr
. - We log
wellFormedStr
to the console using theconsole.log()
method.
JavaScript Program
const str = 'Hello \uD83D\uDE00';
const wellFormedStr = str.toWellFormed();
console.log(wellFormedStr);
Output
Hello 😀
Summary
In this JavaScript tutorial, we learned about toWellFormed() method of String: the syntax and few working examples with output and detailed explanation for each example.