Convert letter to number in JavaScript
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var letter = "h";
var letterPosition = alphabet.indexOf(letter)+1;
EDIT:
Possibility to calculate the letters inside a string, aa=2, ab=3 etc.
function str_split(string, split_length) {
// discuss at: http://phpjs.org/functions/str_split/
// original by: Martijn Wieringa
// improved by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Onno Marsman
// revised by: Theriault
// revised by: Rafał Kukawski (http://blog.kukawski.pl/)
// input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/)
// example 1: str_split('Hello Friend', 3);
// returns 1: ['Hel', 'lo ', 'Fri', 'end']
if (split_length == null) {
split_length = 1;
}
if (string == null || split_length < 1) {
return false;
}
string += '';
var chunks = [],
pos = 0,
len = string.length;
while (pos < len) {
chunks.push(string.slice(pos, pos += split_length));
}
return chunks;
}
function count(string){
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var splitted_string = str_split(string);
var count = 0;
for (i = 0; i < splitted_string.length; i++) {
var letterPosition = alphabet.indexOf(splitted_string[i])+1;
count = count + letterPosition;
}
return count;
}
console.log(count("az")); // returns 27 in the console
If I get you right, the other answers are over complicated:
parseInt('a', 36) - 9; // 1
parseInt('z', 36) - 9; // 26
parseInt('A', 36) - 9; // 1
parseInt('Z', 36) - 9; // 26
Now, to answer the question you asked in the comments:
function sumChars(s) {
var i, n = s.length, acc = 0;
for (i = 0; i < n; i++) {
acc += parseInt(s[i], 36) - 9;
}
return acc;
}
console.log(sumChars("az"))
However, this notation of an integer is space consuming compared to the positional notation. Compare "baz" in both notations:
sumChars("baz") // 29
parseInt("baz", 36) // 14651
As you can see, the amount of letters is the same, but the base 36 integer is way bigger, in other words, base 36 can store bigger numbers in the same space. Moreover, converting a base 10 integer into base 36 integer is trivial in JavaScript:
(14651).toString(36) // "baz"
Finally, be careful when you want to store the values. Although it sounds counterintuitive, base 2 is more compact than base 36. Indeed, one letter occupies at least 8 bits in memory:
(35).toString(2).length // 6 bits long
(35).toString(36).length * 8 // 8 bits long
Therefore I recommend to use "true" integers for storage, it's easy to get back to base 36 anyway.