How could I convert a letter to its corresponding number in JavaScript?
For example:
a = 0 b = 1 c = 2 d = 3
I found this question on converting numbers to letters beyond the 26 character alphabet, but it is asking for the opposite.
Is there a way to do this without a huge array?
The Letter-to-Number Cipher (or Number-to-Letter Cipher or numbered alphabet) consists in replacing each letter by its position in the alphabet , for example A=1, B=2, Z=26, hence its over name A1Z26 .
How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.
You can get a codepoint* from any index in a string using String.prototype.charCodeAt
. If your string is a single character, you’ll want index 0
, and the code for a
is 97 (easily obtained from JavaScript as 'a'.charCodeAt(0)
), so you can just do:
s.charCodeAt(0) - 97
And in case you wanted to go the other way around, String.fromCharCode
takes Unicode codepoints* and returns a string.
String.fromCharCode(97 + n)
* not quite
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With