JavaScript String isWellFormed()
Syntax & Examples


String.isWellFormed() method

The isWellFormed() method of the String class in JavaScript returns a boolean indicating whether the string contains any lone surrogates. Lone surrogates are individual code units that do not form a complete UTF-16 character and are considered ill-formed.


Syntax of String.isWellFormed()

The syntax of String.isWellFormed() method is:

isWellFormed()

This isWellFormed() method of String returns a boolean indicating whether this string contains any lone surrogates.

Return Type

String.isWellFormed() returns value of type Boolean.



✐ Examples

1 Using isWellFormed() to check a well-formed string

In this example, we use the isWellFormed() method to check if a string without any lone surrogates is well-formed.

For example,

  1. We define a string variable str with the value 'Hello'.
  2. We call the isWellFormed() method on str to check if it is well-formed.
  3. The result, which is true, is stored in the variable isWellFormedString.
  4. We log isWellFormedString to the console using console.log() method.

JavaScript Program

const str = 'Hello';
const isWellFormedString = str.isWellFormed();
console.log(isWellFormedString);

Output

true

2 Using isWellFormed() to check a string with lone surrogates

This example demonstrates using the isWellFormed() method to check if a string containing lone surrogates is well-formed.

For example,

  1. We define a string variable str with a lone surrogate '\uD800'.
  2. We call the isWellFormed() method on str to check if it is well-formed.
  3. The result, which is false, is stored in the variable isWellFormedString.
  4. We log isWellFormedString to the console using console.log() method.

JavaScript Program

const str = '\uD800';
const isWellFormedString = str.isWellFormed();
console.log(isWellFormedString);

Output

false

3 Using isWellFormed() to check an emoji string

In this example, we use the isWellFormed() method to check if a string containing emojis is well-formed.

For example,

  1. We define a string variable str with the value '😊'.
  2. We call the isWellFormed() method on str to check if it is well-formed.
  3. The result, which is true, is stored in the variable isWellFormedString.
  4. We log isWellFormedString to the console using console.log() method.

JavaScript Program

const str = '😊';
const isWellFormedString = str.isWellFormed();
console.log(isWellFormedString);

Output

true

Summary

In this JavaScript tutorial, we learned about isWellFormed() method of String: the syntax and few working examples with output and detailed explanation for each example.