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.
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:
- JavaScript Array every method explanation with example
- JavaScript program to check if an array is a subarray of another array
- JavaScript program to delete an item from a set
- JavaScript set add() method explanation with example
- How to check if a date is older than one month or 30 days in JavaScript
- How to convert date to number in JavaScript