Print ASCII Value of a Character in JavaScript
ASCII is a character encoding standard that has been a foundational element in computing for decades. It is used to define characters in a computer. There is a huge table of ASCII values. To print the values in JavaScript In this post, we print the ASCII code of a specific character. One can print the ASCII code for the specific character in JavaScript using several methods which are as follows:
Table of Content
- Using charCodeAt() function
- Using charPointAt() function
- Finding String ASCII with Array.from() method
Using charCodeAt() function
The charCodeAt() function defined in JavaScript returns the specific Unicode number with a specific index of the string.
Example: To demonstrate printing the ASCII code using the charCodeAt() method in JavaScript.
Javascript
let char1 = "B" ; let asciiValue1 = char1.charCodeAt(0); console.log( "ASCII value of '" + char1 + "': " + asciiValue1); |
ASCII value of 'B': 66
Using charPointAt() function
The charPointAt() function also returns the unicode of the string. It returns the specific Unicode number with a specific index of the string.
Example: To demonstrate printing one ASCII character from the string using the charPointAt() function in JavaScript.
Javascript
let text = "Beginner for Beginner" ; let code = text.codePointAt(1); console.log( " ASCII Number = " + code); |
ASCII Number = 101
Using Array.from() method
To find the full string ascii values using the charPointAt() method along with Array.from() method. First we convert string into the array using the Array.from() method then convert each array element into the ASCII value.
Example: To demonstrate printing the whole string ascii values using the Array.from() method.
Javascript
let inputString = "w3wiki" ; let asciiValues = Array.from(inputString, (char) => { return char.charCodeAt(0); }); console.log( "ASCII values of characters in '" + inputString + "': " + asciiValues.join( ", " ) ); |
ASCII values of characters in 'w3wiki': 71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115