How to convert characters to ASCII code and vice versa in JavaScript?

Published November 10, 2020

Contents

Convert character to ASCII code

To convert characters to ASCII, you can use the charCodeAt() string method in JavaScript.

Consider this string,

// string
const str = "Hello John!";

Let's convert the first character of the above string using the charCodeAt() method like this,

// string
const str = "Hello John!";

// convert first character
// of string to ascii by passing the
// index number of character in the string
// as an argument to the method
const asciiVal = str.charCodeAt(0);

console.log(asciiVal); // 72
  • The method accepts a valid index number in the string to get the ASCII value for that character.

See this example live in JSBin.

Convert ASCII code to character

To convert ASCII code to a character, you can use the fromCharCode() Static method in the String class in JavaScript.

Let's say we have ASCII code 65 like this,

// ASCII
const asciiCode = 65;

Now let's convert this ASCII code to a character using the String.fromCharCode() static method like this,

// ASCII
const asciiCode = 65;

// convert ASCII code to character
// by passing the code as an argument
// to the method
const character = String.fromCharCode(asciiCode);

console.log(character); // "A"

See this example live in JSBin

You can also pass more than one ascii code as arguments to the method like this,

// ASCII
const asciiCode = 65;
const asciiCode1 = 66;
const asciiCode2 = 67;

// convert ASCII code to character
// by passing the ascii codes
// as arguments to the method
const character = String.fromCharCode(asciiCode, asciiCode1, asciiCode2);

console.log(character); // "ABC"

See this example live in JSBin.

  • The method accepts valid ASCII codes as arguments to convert to the appropriate character.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter