While working with javascript strings and characters, we often encounter a requirement to get the ASCII value of a character. This article demonstrates easy ways to get the ASCII code of characters using different methods and various example illustrations.
ASCII codes are the numeric value given to the characters and symbols for storing and manipulation by computers and stand for AMERICAN STANDARD CODE FOR INFORMATION INTERCHANGE.
Table of Contents:
Find ASCII Code using charCodeAt()
JavaScript’s charCodeAt() method will return an integer ranging from 0 and 65535 that depicts the UTF-16 code value at the given index.
syntax: charCodeAt(_index)
Where _index is the integer >=0 and < the length of the string; the default value is 0.
Example:-
Frequently Asked:
Find the ASCII codes for ‘p’, ‘%’, ‘8’
Code:-
//function to find the ASCII Code Value function getASCIICode(_char) { return _char.charCodeAt(0); } //examples let char1 = 'p'; let char2 = '%'; let char3 = '8'; //usage of the function getASCIICode() console.log(getASCIICode(char1)); console.log(getASCIICode(char2)); console.log(getASCIICode(char3));
Output:-
112 37 56
Find ASCII Code using codePointAt()
JavaScript’s codePointAt() method will return a non-negative integer, the Unicode code point value at the given position
syntax: codePointAt(_position)
Where _position is the position of the character from string to return the code point value from.
Example:-
Find the ASCII codes for ‘p’, ‘%’, ‘8’
Code:-
//function to find the ASCII Code Value function getASCIICode(_char) { return _char.codePointAt(0); } //examples let char1 = 'p'; let char2 = '%'; let char3 = '8'; //usage of the function getASCIICode() console.log(getASCIICode(char1)); console.log(getASCIICode(char2)); console.log(getASCIICode(char3));
Output:-
112 37 56
Note that if the Unicode code point cannot be represented in a single UTF-16 code unit as it is greater than 0xFFFF then codePointAt() is used.
I hope this article helped you get the ASCII value of characters in the javascript string. Good Luck !!!