Count with A, B, C, D instead of 0, 1, 2, 3, ... with JavaScript
count, counter, javascript, numbers
Solution
Here's a simple recursive function to convert the numbers to letters.
It's one-based, so 1 is A, 26 is Z, 27 is AA.
function toLetters(num) {
"use strict";
var mod = num % 26,
pow = num / 26 | 0,
out = mod ? String.fromCharCode(64 + mod) : (--pow, 'Z');
return pow ? toLetters(pow) + out : out;
}
Here's a matching function to convert the strings back to numbers:
function fromLetters(str) {
"use strict";
var out = 0, len = str.length, pos = len;
while (--pos > -1) {
out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - 1 - pos);
}
return out;
}
A test: http://jsfiddle.net/St6c9/
Problem
This is probably an unusual request, but for my script I need a function that increments by letter instead of number. For example: This is a numeric example: ``` var i = 0; while(condition){ window.write('We are at '+i); ++i; } ``` Essentially, I want to count with letters, like Microsoft Excel does, instead of numbers. So instead of printing "We are at 0", "We are at 1", "We are at 2", etc., I need to print "We are at A", "We are at B", "We are at C", etc. To mimic Excel (the only example I can think of), after reaching index 25 (Z), we could move on to 'AA', 'AB', 'AC', etc. So it would work great like so: ``` var i = 0; while(condition){ window.write('We are at '+toLetter(i)); ++i; } ``` Even better if somebody can write a function that then converts a letter back into a digit, i.e. toNumber('A') = 0 or toNumber('DC') = 107 (I think). Thanks!