Convert a character to its ASCII code in JavaScript
This post will discuss how to convert a character to its ASCII code in JavaScript.
For example, the ACSII code of 'A'
is 65, '0'
is 48, 'a'
is 97, etc.
1. Using String.charCodeAt()
function
The charCodeAt() method returns UTF-16
code unit at the specified index. This returns an integer between 0 and 65535. The first 128 Unicode code points (0 to 127) match the ASCII character set.
The following example returns the Unicode value for 'A'
, which is 65.
1 2 3 4 5 6 7 8 9 |
var ch = 'A'; var index = 0; var i = ch.charCodeAt(index); console.log(i); /* Output: 65 */ |
To get the reverse, you can use the fromCharCode() method, which returns a string from a specified sequence of code points.
1 |
console.log(String.fromCharCode(65, 66)); // returns 'AB' |
2. Using String.codePointAt()
function
The codePointAt() method returns a number representing the code point value of the character at the given index. The following code returns the Unicode value for 'a'
, which is 97.
1 2 3 4 5 6 7 8 9 |
var ch = 'a'; var pos = 0; var i = ch.codePointAt(pos); console.log(i); /* Output: 97 */ |
It is different from the charCodeAt()
method as it can handle code point which cannot be represented in a single UTF-16
code unit (i.e., characters greater than 0xFFFF
).
1 2 |
console.log('????'.codePointAt(0)); // 68181 console.log('\uD800\uDC00'.codePointAt(0)); // 65536 |
To do the reverse, you can use the fromCodePoint() method, which returns a string created using the specified sequence of code points.
1 |
console.log(String.fromCodePoint(68181)); // '????' |
That’s all about converting a character to its ASCII code in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)