Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  99] [ 2]  / answers: 1 / hits: 165122  / 10 Years ago, tue, march 25, 2014, 12:00:00

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?


More From » javascript

 Answers
5

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


[#71797] Sunday, March 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
zaynerogerb questions
;