Convert number to alphabet letter
Asked Answered
D

9

25

I want to convert a number to its corresponding alphabet letter. For example:

1 = A
2 = B
3 = C

Can this be done in javascript without manually creating the array? In php there is a range() function that creates the array automatically. Anything similar in javascript?

Dutcher answered 21/3, 2016 at 11:22 Comment(3)
Can you share sample input and outputSealy
hint: check for corresponding ASCII values for lettersValetudinary
I have an answer here: stackoverflow linkBedel
C
48

Yes, with Number#toString(36) and an adjustment.

var value = 10;

document.write((value + 9).toString(36).toUpperCase());
Cedilla answered 21/3, 2016 at 11:27 Comment(3)
What if the number > 26?Centriole
@Fr0zenFyr, then you get a wrong result. you need a check before and a rule what should happen in this case.Cedilla
@CodeBrauer I don't understand what you mean by this. How is this applicable to the example code? Yes, 36 % 26 is 10 but it's hardly straightforward to code the numeric value of the letter you're looking for that way, in if you do something like 36 % 256 you'll still get a result > 26.Goto
W
28

You can simply do this without arrays using String.fromCharCode(code) function as letters have consecutive codes. For example: String.fromCharCode(1+64) gives you 'A', String.fromCharCode(2+64) gives you 'B', and so on.

Wheeling answered 21/3, 2016 at 11:28 Comment(1)
I use it like this: String.fromCharCode(1 + 'A'.charCodeAt(0))Aeroembolism
P
11

Snippet below turns the characters in the alphabet to work like numerical system

1 = A
2 = B
...
26 = Z
27 = AA
28 = AB
...
78 = BZ
79 = CA
80 = CB

var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var result = ""
function printToLetter(number){
    var charIndex = number % alphabet.length
    var quotient = number/alphabet.length
    if(charIndex-1 == -1){
        charIndex = alphabet.length
        quotient--;
    }
    result =  alphabet.charAt(charIndex-1) + result;
    if(quotient>=1){
        printToLetter(parseInt(quotient));
    }else{
        console.log(result)
        result = ""
    }
}

I created this function to save characters when printing but had to scrap it since I don't want to handle improper words that may eventually form

Pervious answered 3/2, 2020 at 5:10 Comment(3)
Would be nice if you'd add some explanation about the codeAphesis
result = "" should be deleted for this to work. Otherwise, great!Cabezon
This case doesn't really call for recursion, a while loop is betterJerol
A
8

Just increment letterIndex from 0 (A) to 25 (Z)

const letterIndex = 0
const letter = String.fromCharCode(letterIndex + 'A'.charCodeAt(0))

console.log(letter)
Argus answered 22/12, 2021 at 11:36 Comment(1)
smart, I like itNotochord
O
4

UPDATE (5/2/22): After I needed this code in a second project, I decided to enhance the below answer and turn it into a ready to use NPM library called alphanumeric-encoder. If you don't want to build your own solution to this problem, go check out the library!


I built the following solution as an enhancement to @esantos's answer.

The first function defines a valid lookup encoding dictionary. Here, I used all 26 letters of the English alphabet, but the following will work just as well: "ABCDEFG", "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "GFEDCBA". Using one of these dictionaries will result in converting your base 10 number into a base dictionary.length number with appropriately encoded digits. The only restriction is that each of the characters in the dictionary must be unique.

function getDictionary() {
    return validateDictionary("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

    function validateDictionary(dictionary) {
        for (let i = 0; i < dictionary.length; i++) {
            if(dictionary.indexOf(dictionary[i]) !== dictionary.lastIndexOf(dictionary[i])) {
                console.log('Error: The dictionary in use has at least one repeating symbol:', dictionary[i])
                return undefined
            }
        }
        return dictionary
    }
}

We can now use this dictionary to encode our base 10 number.

function numberToEncodedLetter(number) {
    //Takes any number and converts it into a base (dictionary length) letter combo. 0 corresponds to an empty string.
    //It converts any numerical entry into a positive integer.
    if (isNaN(number)) {return undefined}
    number = Math.abs(Math.floor(number))

    const dictionary = getDictionary()
    let index = number % dictionary.length
    let quotient = number / dictionary.length
    let result
    
    if (number <= dictionary.length) {return numToLetter(number)}  //Number is within single digit bounds of our encoding letter alphabet

    if (quotient >= 1) {
        //This number was bigger than our dictionary, recursively perform this function until we're done
        if (index === 0) {quotient--}   //Accounts for the edge case of the last letter in the dictionary string
        result = numberToEncodedLetter(quotient)
    }

    if (index === 0) {index = dictionary.length}   //Accounts for the edge case of the final letter; avoids getting an empty string
    
    return result + numToLetter(index)

    function numToLetter(number) {
        //Takes a letter between 0 and max letter length and returns the corresponding letter
        if (number > dictionary.length || number < 0) {return undefined}
        if (number === 0) {
            return ''
        } else {
            return dictionary.slice(number - 1, number)
        }
    }
}

An encoded set of letters is great, but it's kind of useless to computers if I can't convert it back to a base 10 number.

function encodedLetterToNumber(encoded) {
    //Takes any number encoded with the provided encode dictionary 

    const dictionary = getDictionary()
    let result = 0
    let index = 0

    for (let i = 1; i <= encoded.length; i++) {
        index = dictionary.search(encoded.slice(i - 1, i)) + 1
        if (index === 0) {return undefined} //Attempted to find a letter that wasn't encoded in the dictionary
        result = result + index * Math.pow(dictionary.length, (encoded.length - i))
    }

    return result
}

Now to test it out:

console.log(numberToEncodedLetter(4))     //D
console.log(numberToEncodedLetter(52))    //AZ
console.log(encodedLetterToNumber("BZ"))  //78
console.log(encodedLetterToNumber("AAC")) //705

UPDATE

You can also use this function to take that short name format you have and return it to an index-based format.

function shortNameToIndex(shortName) {
    //Takes the short name (e.g. F6, AA47) and converts to base indecies ({6, 6}, {27, 47})

    if (shortName.length < 2) {return undefined}    //Must be at least one letter and one number
    if (!isNaN(shortName.slice(0, 1))) {return undefined}  //If first character isn't a letter, it's incorrectly formatted

    let letterPart = ''
    let numberPart= ''
    let splitComplete = false
    let index = 1

    do {
        const character = shortName.slice(index - 1, index)
        if (!isNaN(character)) {splitComplete = true}
        if (splitComplete && isNaN(character)) {
            //More letters existed after the numbers. Invalid formatting.
            return undefined    
        } else if (splitComplete && !isNaN(character)) {
            //Number part
            numberPart = numberPart.concat(character)
        } else {
            //Letter part
            letterPart = letterPart.concat(character)
        }
        index++
    } while (index <= shortName.length)

    numberPart = parseInt(numberPart)
    letterPart = encodedLetterToNumber(letterPart)

    return {xIndex: numberPart, yIndex: letterPart}
}
Osmond answered 20/4, 2021 at 16:26 Comment(3)
Great answer! Because it can be used with PHP script to decode and encode. So it can be cross language validated. Using this code: #7664621 Just had to fix PHP code to from +1 and -1, on PHP results and function input. And it works perfectly matches.Trudytrue
Shorten number by unique key order of alphanumeric: Try out: cutt.ly/URaPxH7 Improvements can be on to PHP code.Trudytrue
I needed this for a second project, so I decided to just make it into a library. Check it out: npmjs.com/package/alphanumeric-encoderOsmond
P
1

There is a single line function numAbbr for convert numbers to strings like

1 => A
2 => B
...
26 => Z
27 => AA
28 => AB
...
702 => ZZ
703 => AAA
const numAbbr = num => num <= 0 ? '' : numAbbr(Math.floor((num - 1) / 26)) + String.fromCharCode((num - 1) % 26 + 65);

and opposite function abbrNum converts strings like AAA to numbers


const abbrNum = abbr => abbr.toUpperCase().split("").reduce((acc, val) => acc * 26 + val.charCodeAt(0) - 64, 0);
Pierrette answered 5/3, 2023 at 16:11 Comment(1)
See my answer for the same function as numAbbr without recursionJerol
J
0

The code answers on this question are really overly complicated when it can be achieved with a simple loop

function colToLetter(number){
  let result = '';
  // number = number - 1; // If starting from 1
  do {
    const letter = String.fromCharCode(65 + (number % 26));
    result = letter + result;
    number = Math.floor(number / 26) - 1;
  } while (number >= 0)
  return result;
}

console.log(colToLetter(0));
console.log(colToLetter(25));
console.log(colToLetter(26));
console.log(colToLetter(702));
console.log(colToLetter(728));

This provides excel like numbering

Jerol answered 22/6, 2023 at 17:41 Comment(2)
Excel numbering starting from 1 not from 0Pierrette
No it starts with A, then B.. Z, AA, AB, etc, it so happens that in most programming languages you start indexing from 0 like is the case for js, so it translates to first index is A, there is a comment for depending on where you want to start indexing anywaysJerol
T
0

String.fromCharCode(code) works pretty well without the need of loops and arrays.

   var index = 1;
   
console.log(String.fromCharCode(index + 64));
Taut answered 24/6 at 9:4 Comment(0)
S
-1

this can help you

static readonly string[] Columns_Lettre = new[] { "A", "B", "C"};

public static string IndexToColumn(int index)
    {
        if (index <= 0)
            throw new IndexOutOfRangeException("index must be a positive number");

        if (index < 4)
            return Columns_Lettre[index - 1];
        else
            return index.ToString();
    }
Sheeb answered 4/5, 2016 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.