JavaScript fromCodePoint(...codePoints) method


The String.fromCodePoint(...codePoints) method in JavaScript is used to create a string from one or more Unicode code points. This method allows you to represent characters from the full range of Unicode, including those that cannot be represented using the older String.fromCharCode() method, which only supports values from 0 to 65535 (Basic Multilingual Plane).

Syntax:

String.fromCodePoint(...codePoints)
  • ...codePoints: A list of one or more Unicode code points (numeric values) that you want to convert into a string.

Return Value:

  • Returns a string created by concatenating the characters represented by the provided Unicode code points.

Example 1: Basic Usage

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

In this example, the method converts the code points 65, 66, and 67 into the string "ABC".

Example 2: Including Special Characters

You can create strings with special characters by using their corresponding code points.

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

Here, the character codes correspond to the characters !, @, #, $, and %.

Example 3: Unicode Characters

fromCodePoint() can handle a wider range of Unicode characters, including emojis and symbols that fall outside the Basic Multilingual Plane.

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

In this case, the method converts the Unicode code point for the grinning face emoji into a string.

Example 4: Using Multiple Code Points

You can pass multiple code points to create a longer string.

let charStr = String.fromCodePoint(0x1F600, 0x1F601, 0x1F602); // 😀😁😂 console.log(charStr); // "😀😁😂"

Here, the method generates a string containing three emojis.

Example 5: Handling Non-Character Code Points

If you provide a number that does not correspond to a valid character, fromCodePoint() will still return a string, but it may be an unprintable character.

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

Summary:

  • The String.fromCodePoint(...codePoints) method creates a string from one or more Unicode code points.
  • It supports a much broader range of characters than String.fromCharCode(), including characters beyond the Basic Multilingual Plane.
  • This method is particularly useful for generating strings with a wide variety of characters, including emojis and other symbols.
  • It is recommended to use fromCodePoint() when dealing with Unicode characters that may require code points greater than 65535.