The fromCharCode() method allows JavaScript to create a string from a sequence of UTF-16 character codes and is useful for dealing with characters that are difficult to type or need to be escaped.
String.fromCharCode()
Note: This method is a static method of the object named string and is not an inherited method of a variable that is a string. If you attempt to call the method as if it were a string variable, you will generate the following error:
fromCharCode is not a function
The fromCharCode() method must be called as followed:
var MyString = String.fromCharCode(84,101,120,116);
Full Example of the fromCharCode() Method:
<!DOCTYPE html>
<html lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>JavaScript String fromCharCode Method Example</title>
</head>
<body>
<script>
var MyText = "abc";
MyText += String.fromCharCode(49,50,51);
console.log(MyText);
</script>
</body>
</html>
The following text is printed to the console:
abc123
Valid Character Input Types for fromCharCode()
This method will accept character formatted three different ways:
Note: Each example will produce the word “HELLO.”
Decimals:
MyString = String.fromCharCode(72,69,76,76,79,46);
Hex Values:
MyString = String.fromCharCode(0x48,0x45,0x4c,0x4c,0x4f,0x2e);
Octal Values:
MyString = String.fromCharCode(0o110,0o105,0o114,0o114,0o117,0o56);
Limitations of the fromCharCode() Method
This method will not work correctly with escaped Unicode characters, but this isn’t a problem as a string can be assigned an escaped Unicode sequence instead.
var MyString = '\u0048\u0045\u004C\u004C\u004F\u002E';
//HELLO.
It is recommended that if you are working with complex characters that are outside of the standard set of characters known as the BMP (Base Multilingual Plane) that you use the fromCodePoint() method instead.
This is due to the limitation of the fromCharCode() method, which is limited to 16-bit values.
If for one reason or another, you must use fromCharCode() with characters outside of the BMP, then you can substitute a surrogate pair or character to represent it.