JavaScript String. toWellFormed() Method
Last Updated :
27 Aug, 2024
One very common job in the world of JavaScript is working with strings, and sometimes it's really important to ensure that those strings are well-formed. The toWellFormed method is rather one of the new ones in JavaScript. It was added to help developers work with strings containing Unicode characters in a more powerful way. It will ensure that the string represents valid Unicode, which could be quite beneficial for developers who wish to work with a web application that is internationalized and contains user-generated content.
Syntax
string.toWellFormed();
Parameters:
The toWellFormed() method does not take any parameters.
Return Value:
The toWellFormed() operation. The operation returns a new string, which will be an identical copy of the string if the string is already well formed. If a surrogate codepoint is found in the string, it is replaced by the Unicode replacement character (U+FFFD).
Example 1: In this example, the original string contains a lone surrogate (\uD800), which is not a valid Unicode character on its own. When toWellFormed() is called, it replaces the lone surrogate with the replacement character (�).
JavaScript
const stringWithLoneSurrogates = '\uD800';
const wellFormedString = stringWithLoneSurrogates.toWellFormed();
console.log(wellFormedString);
Output: �
Example 2: Here, the string is already well-formed with valid Unicode characters, including the globe emoji. Calling toWellFormed() on this string returns a copy of the original string without any changes.
JavaScript
const validUnicodeString = 'Hello, \uD83C\uDF0D!';
const wellFormedString = validUnicodeString.toWellFormed();
console.log(wellFormedString);
Output: Hello, Globe emoji
Example 3: In this case, the string contains both valid characters and a lone surrogate (\uD800). The toWellFormed() method replaces the lone surrogate with the replacement character, resulting in a well-formed string.
JavaScript
const mixedString = 'Hello, \uD800World!';
const wellFormedString = mixedString.toWellFormed();
console.log(wellFormedString);
Output: Hello, �World!
Supported Browsers