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:
...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
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.
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.
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.
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.
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.