In theory, no matter what the input is, the output should be unchanged:
String.fromCharCode("a".charCodeAt(0)); //"a"
This makes sense because I'm just trying to get the char code of a character, and then casting it back to a character.
However when I try with this character, it breaks:
//"🌀": 55356
String.fromCharCode("🌀".charCodeAt(0)); //"�" (65533)
(Note that I actually highlighted the string and pasted it into the next line. It changed to �
by itself for some reason.)
Why is this happening and how can I fix this?
I noticed that there is a new method in ES6, String.fromCodePoint()
but it is not supported every browser except Firefox.
charAt VS charCodeAt VS fromCharCodeThe method charAt() returns a character from a string by specifying its index. charCodeAt() returns the Unicode value of specified character inside a string. The method fromCharCode converts Unicode values into characters.
The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
The charCodeAt() method returns the Unicode of the character at a specified index (position) in a string. The index of the first character is 0, the second is 1, .... The index of the last character is string length - 1 (See Examples below).
fromCharCode() method converts Unicode values to characters. The String. fromCharCode() is a static method of the String object. The syntax is always String.
It does not change.
> String.fromCharCode("🌀".charCodeAt(0)).charCodeAt(0)
55356
And you can check all by:
for (var i = 0; i <= 65535; i++) {
if (String.fromCharCode(i).charCodeAt(0) !== i) {
console.log('error', i, String.fromCharCode(i));
}
}
Why you saw �
is because �
(65533) is
used to replace a character whose value is unknown or unrepresentable in unicode.
It is called REPLACEMENT CHARACTER.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With