2

What would be the best way, in javascript, to generate a short, uniqueletter ID from a number. For example 1 would be A, 2 would be B, and 27 would be AA.

user2117190
  • 545
  • 2
  • 6
  • 10

1 Answers1

5

Base26 Alpha-encode the number. This will convert it from a number to a text representation, just like in Excel spreadsheets.

See here for a code representation of a suitable algorithm: http://frugalcoder.us/post/2011/02/24/Convert-an-integer-to-a-base26-alpha-string.aspx

function intToAlpha26String(input) {
    input = (+input).toString(26);
    var ret = [];
    while (input.length) {
        var a = input.charCodeAt(input.length-1);
        if (input.length > 1)
            input = (parseInt(input.substr(0, input.length - 1), 26) - 1).toString(26);
        else
            input = "";

        if (a >= 48/*'0'*/ && a <= 57 /*'9'*/)
            ret.unshift(String.fromCharCode(a + 49)); //raise to += 'a'
        else
            ret.unshift(String.fromCharCode(a + 10)); //raise + 10 (make room for 0-9)
    }
    return ret.join('').toUpperCase();
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501