Open In App

JavaScript String isWellFormed() Method

JavaScript String.isWellFormed() method is used to check if the string contains a lone surrogate or not. A lone surrogate is a string that contains Unicode characters in the range 0xD800–0xDBFF and 0xDC00–0xDFFF. It returns trues if the lone surrogate is not present. If the string is not well-formed it will give an error if we use the encodeURI() method on it.

Syntax:



isWellFormed()

Parameters: It does not take any parameter

Return Value: A boolean, true if no lone surrogate is present, and false if the lone surrogate is present.



Example 1: This example uses the isWellFormed() method on strings.




const str1 = "ab\uD800";
const str2 = "new\uD800";
const str3 = "hello";
 
console.log(str1.isWellFormed());
console.log(str2.isWellFormed());
console.log(str3.isWellFormed());

Output:

false
false
true

Example 2: This example will perform the encodeURI function only on well-formed strings.




const badFormed = "ab\uD800";
const wellFormed = "hello";
 
function checkFormation(str) {
    if(str.isWellFormed()){
        console.log(encodeURI(str))
    }
}
checkFormation(wellFormed);
checkFormation(badFormed);

Output:

hello

Supported Browsers:

We have a complete list of Javascript string methods, to check those please go through this Javascript String reference article.

Article Tags :