Description

The JavaScript method fromCharCode() returns a string created from a sequence of characters using their UTF-16 code units.

Syntax

The method fromCharCode() is a static method, so it must be called directly using the String class.

String.fromCharCode(num1, num2, ..., numN)

Parameters

The method accepts the below parameters.

num1, num2, ..., numN

  • It takes an arbitrary number of UTF-16 character code values.
  • If the number is not between 0 and 65535, the number is ignored.

Result

The method returns a string (not a string object) created from the sequence of characters using their UTF-16 code units.

 


Example 1: Using the Method with Decimal Values

The method generates a string from a sequence of characters using their UTF-16 code units decimal values.

// Generating a string "Hello World!" using UTF-16 code units decimal values
var str = String.fromCharCode(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33);

document.write(str);    // Prints: Hello World!

Output:

Hello World!

 


Example 2: Using the Method with Hexadecimal Values

Also, the method generates a string from a sequence of characters using their UTF-16 code units hexadecimal values.

// Generating a string "Hello World!" using UTF-16 code units hexadecimal values
var str = String.fromCharCode(0x0048, 0x0065, 0x006C, 0x006C, 0x006F, 0x0020, 0x0057, 0x006F, 0x0072, 0x006C, 0x0064, 0x0021);

document.write(str);    // Prints: Hello World!

Output:

Hello World!

 


Example 3: Using the Method with Invalid Values

Also, the method generates an error for invalid Unicode point values.

// Generating a string "Hello World!" using Unicode points hexadecimal values
var str = String.fromCharCode(-10);

document.write(str);    // Prints nothing as -10 is invalid and ignored

Output:

 

Overall

JavaScript method fromCharCode() returns a string created from a sequence of characters using their UTF-16 code units.

Related Links