JavaScript fromCharCode(...codes) method


The String.fromCharCode(...codes) method in JavaScript is used to create a string from a sequence of Unicode character codes. This method takes one or more numeric values representing character codes and returns a string composed of the characters corresponding to those codes.

Syntax:

String.fromCharCode(...codes)
  • ...codes: A list of one or more Unicode values (numeric character codes) that you want to convert into a string.

Return Value:

  • Returns a string created by concatenating the characters represented by the provided Unicode character codes.

Example 1: Basic Usage

let charStr = String.fromCharCode(65, 66, 67); console.log(charStr); // "ABC"

In this example, the fromCharCode() method converts the character codes 65, 66, and 67 into the string "ABC".

Example 2: Using Multiple Character Codes

You can pass multiple character codes to create a longer string.

let charStr = String.fromCharCode(72, 101, 108, 108, 111); console.log(charStr); // "Hello"

Here, the method converts the character codes for the letters in "Hello" into a string.

Example 3: Including Special Characters

You can also create strings with special characters by using their corresponding character codes.

let charStr = String.fromCharCode(33, 64, 35, 36, 37); console.log(charStr); // "!@#$%"

In this case, the character codes correspond to the characters !, @, #, $, and %.

Example 4: Unicode Characters

fromCharCode() can also be used to generate characters from a wider range of Unicode codes.

let charStr = String.fromCharCode(0x1F600); // 😀 (grinning face emoji) console.log(charStr); // "😀"

Here, the method converts the Unicode code for the grinning face emoji into a string.

Example 5: Handling Non-Character Codes

If you provide a number that does not correspond to a valid character, fromCharCode() will return an empty string or a non-printable character.

let charStr = String.fromCharCode(1000); // Some valid character console.log(charStr); // "Ϩ" (Greek letter Heta)

Summary:

  • The String.fromCharCode(...codes) method creates a string from one or more Unicode character codes.
  • It can handle a variety of characters, including letters, special symbols, and even emojis.
  • This method is useful for generating strings programmatically when you need to work with character codes directly.
  • For Unicode characters outside the Basic Multilingual Plane (U+10000 and above), consider using String.fromCodePoint() instead, which handles larger Unicode values.