How to get the ASCII value of a character#

To get the ASCII value of a character, use the charCodeAt instance method of the String JavaScript object. Example:

[run]

var s = 'A';
console.log(s.charCodeAt(0));
// 65

[/run]

To convert a string of characters to ASCII values, you can do something like this:

[run]

'apple'.split('').forEach(function (c) {
  console.log(c + ': ' + c.charCodeAt(0));
});

[/run]

To convert an ASCII value to its corresponding character use the fromCharCode static method of the String JavaScript object. Example:

[run]

console.log(String.fromCharCode(65));
// 'A'

[/run]

Reference#

  1. MDN - String​.prototype​.char​CodeAt()
  2. MDN - String​.from​Char​Code()
Tweet this | Share on LinkedIn |