Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count with A, B, C, D instead of 0, 1, 2, 3, ... with JavaScript

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!

like image 700
M Miller Avatar asked Jun 18 '12 19:06

M Miller


People also ask

How do you count in JavaScript?

The count() method counts the number of times console. count() is called. The count() method this number to the console.

How do I convert letters to numbers?

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 .

WHAT IS A to Z in numbers?

Conversion Table A = 1 B = 2 C = 3 D = 4 E = 5 F = 6 G = 7 H = 8 I = 9 J = 10 K =11 L = 12 M = 13 N =14 O =15 P = 16 Q =17 R =18. Page 1. Conversion Table.


2 Answers

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/

like image 96
Dagg Nabbit Avatar answered Oct 01 '22 23:10

Dagg Nabbit


Something like this you mean?

function num2chars(num, upper){
 num2chars.letters = num2chars.letters || 'abcdefghijklmnopqrstuvwxyz'.split('');
 var ret = repeat(num2chars.letters[num%26],Math.floor(num/26));

 function repeat(chr,n){
  if (n<1) {return chr;}
  return new Array(n+1).join(chr);
 }

 return upper ? ret.toUpperCase() : ret;
}
//usage
while(i<104){
 console.log(num2chars((i+=1),true));
}
//=> A..Z, AA..ZZ, AAA..ZZZ
like image 31
KooiInc Avatar answered Oct 02 '22 00:10

KooiInc