How to find the ASCII value of a character in JavaScript

How to find the ASCII value of a character in JavaScript:

In this post, we will learn how to find the ASCII value of a character in JavaScript. We will use charCodeAt and codePointAt methods to find the ASCII values.

String.charCodeAt:

charCodeAt is an inbuilt method of javascript String class. This method returns the UTF-16 code unit at a given index. It can return a value between 0 to 65535.

We can use this method to get the ASCII value of a character.

For example,

let c = 'a';

console.log(c.charCodeAt(0));

We are passing the index as 0 because we are using this method with only one character. It will print 97.

Javascript find ASCII of a character

We can also use it with a string to find the ASCII of a specific character at a given index.

If you don’t provide any index, it takes 0 by default. If you provide an index which is not in range, it returns NaN.

String.codePointAt:

codePointAt method returns the UTF-16 code point value. It takes the index as the parameter. Let’s try codePointAt to find the ASCII value for a character:

let c = 'a';

console.log(c.codePointAt(0));

It will print 97. Similar to the above example, we are passing 0 as the index. If you don’t pass any index, it takes 0 by default. If the index is out of range, it returns undefined.

We can also use codePointAt to find the ASCII value for a character in a string by using its index.

let c = 'and';

console.log(c.codePointAt(2));

It will print 100, i.e the ASCII of d.

You might also like: