For character A, its ASCII code is 65
B = 66
a = 97
b = 98
0 = 48
For each character, there will be a unique ASCII code.
charCodeAt() method takes the index of the character and returns UTF-16 code for the given index.
The first 128 Unicode points from 0 to 127 are used to match the ASCII character set.
Look at the below program.
var chracter="B"; var index = 0; var asciiCode = chracter.charCodeAt(index); console.log(asciiCode);
ASCII code for character B is 66. The same has been produced in the output console.
When the String characters are having special characters such as codepoints then the charCodeAt() method does not work. In this case, you need to use the codePointAt() method.
codePointAt() method returns the integer value in between 0 and 65535.
Look at the below example script using codePointAt() function.
"The character code 101 is equal to e" 65
If you want to get the character from the ASCII codes, use the String.fromCharCode() method from the String object.
console.log(String.fromCharCode(65, 66)); console.log(String.fromCharCode(67, 68)); console.log(String.fromCharCode(69, 70));
Any no of arguments can be passed to
fromCharCode() method and all characters are returned as String object by concatenating all characters of the given ASCII codes.
Look at the output how the fromCharCode() method has generated the output.
AB CD EF
String.fromCodePoint() is used to get the string from the given set of code points sequence.
This method also takes any no of arguments. Look at the below example with different arguments.
console.log(String.fromCodePoint(9731)); console.log(String.fromCodePoint(9731, 9733)); console.log(String.fromCodePoint(9735, 9737)); console.log(String.fromCodePoint(9731, 9733, 9842)); console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));
"☃" "☃★" "☇☉" "☃★♲" "☃★♲你"
In this article, we’ve seen how to convert the character to ascii code in java script and vice versa with examples.