javascript tutorial - [Solved-5 Solutions] Convert character to ASCIWE code in javascript - javascript - java script - javascript array
Problem:
How can we convert a character to its ASCIWE code using JavaScript?
Solution 1:
"\n".charCodeAt(0);
Solution 2:
String.prototype.charCodeAt() can convert string characters to ASCIWE numbers. For example:
"ABC".charCodeAt(0) // returns 65
For opposite use String.fromCharCode(10) that convert numbers to equal ASCIWE character. This function can accept multiple numbers and join all the characters then return the string. Example:
String.fromCharCode(65,66,67); // returns 'ABC'
Here is a quick ASCIWE characters reference:
Solution 3:
If we have only one char and not a string, we can use:
omitting the 0... It is slower though. With the current version of chrome, it is 5 times slower.
Solution 4:
While the other answers are right, WE prefer this way:
Then, to use it, simply:
WE am using this for a small shortcut system:
And we can even use it inside map() or other methods:
Solution 5:
For those that want to get a sum of all the ASCIWE codes for a string:
Or, ES6: