Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to set alphabet variable like Excel columns

Tags:

javascript

I'm looking for a nice way to have a variable alpha that would increment as follow: when x=0 -> alpha = "A"; x=1 -> alpha = "B"; ... x=25 -> alpha = "Z"; x=26 -> alpha = "AA"; x=27 -> alpha = "AB"

like image 707
ncohen Avatar asked Sep 19 '25 22:09

ncohen


2 Answers

You could use toString with base 36 for converting to the wanted letters.

function convert(n) {
    var result = '';
    do {
        result = (n % 26 + 10).toString(36) + result;
        n = Math.floor(n / 26) - 1;
    } while (n >= 0)
    return result.toUpperCase();
}

//           A  B   Z  AA  AB   CZ   DXH
console.log([0, 1, 25, 26, 27, 103, 3335].map(convert));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 181
Nina Scholz Avatar answered Sep 21 '25 11:09

Nina Scholz


EDITED

OK sorry I just didn't understand your need at first. Here is a working code.

Try this:

var x = 807;
var alpha = '';
var alphabetLength = 26;


var y = x.toString(alphabetLength);
chars = y.split('');
for (var i=0; i < chars.length; i++ ) {
	var charFactor = 65;
	var curChar = chars[i];
	if (isNaN(curChar)) {
	
		alpha += String.fromCharCode(curChar.toUpperCase().charCodeAt() + 10);
	} else {
		if ( i < chars.length-1) {
			charFactor--;
		}
		alpha += String.fromCharCode(parseInt(curChar) + charFactor);
	}
}

console.log(alpha)
like image 33
Z-Bone Avatar answered Sep 21 '25 12:09

Z-Bone