The fromCodePoint() method allows JavaScript to create a string from a sequence of UTF-16 or UTF-32 character codes and is useful for dealing with characters that are difficult to type or need to be escaped.
String.fromCodePoint()
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 descendant of the string object, you will generate the following error:
fromCodePoint is not a function
The following code example is a simple demonstration of the fromCodePoint() 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 fromCodePoint Method Example</title>
</head>
<body>
<script>
var MyText = "abc";
MyText += String.fromCodePoint(49,50,51);
console.log(MyText);
</script>
</body>
</html>
The following text is printed to the console:
abc123
Valid Character Input Types for fromCodePoint()
This method will accept character formatted three different ways:
Note: Each example will produce the word “HELLO.”
Decimals:
MyString = String.fromCodePoint(72,69,76,76,79,46);
Hex Values:
MyString = String.fromCodePoint(0x48,0x45,0x4c,0x4c,0x4f,0x2e);
Octal Values:
MyString = String.fromCodePoint(0o110,0o105,0o114,0o114,0o117,0o56);
Limitations of fromCodePoint()
This method will not work correctly with escaped Unicode characters and if you attempt to you will generate the following error message:
Uncaught RangeError: NaN is not a valid code point
Instead a string can be assigned an escaped Unicode sequence as follows:
var MyString = '\u0048\u0045\u004C\u004C\u004F\u002E';
//HELLO.
Difference of fromCodePoint() and fromCharCode()
The fromCodePoint() method should work with all valid UTF-32 values and it is recommended over fromCharCode() in almost all circumstances.
If the code provided to this method is outside of the range of valid UTF-32 values, the following error message will be generated:
Uncaught RangeError: "The Value" is not a valid code point