Number to alphabets in JavaScript

We are required to write a JavaScript function that takes in a string of any variable length that represents a number.

Our function is supposed to convert the number string to the corresponding letter string.

For example ? If the number string is ?

const str = '78956';

Then the output should be ?

const output = 'ghief';

If the number string is ?

const str = '12345';

Then the output string should be ?

const output = 'lcde';

Notice how we didn't convert 1 and 2 to alphabets separately because 12 also represents an alphabet. So we have to consider this case while writing our function.

We, here, assume that the number string will not contain 0 in it, if it contains though, 0 will be mapped to itself.

Mapping Logic

The conversion follows this pattern:

  • 1-26 maps to a-z (where 1='a', 2='b', ..., 26='z')
  • Two-digit numbers (10-26) take priority over single digits
  • If a two-digit combination exceeds 26, use single digits instead

Example Implementation

Let us write the code for this function ?

const str = '12345';
const str2 = '78956';

const convertToAlpha = numStr => {
    const legend = '0abcdefghijklmnopqrstuvwxyz';
    let alpha = '';
    
    for(let i = 0; i < numStr.length; i++){
        const el = numStr[i], next = numStr[i + 1];
        
        // Check if two-digit number is valid (10-26)
        if(+(el + next) <= 26 && +(el + next) >= 10){
            alpha += legend[+(el + next)];
            i++; // Skip next digit as it's used
        }
        else{
            alpha += legend[+el];
        };
    };
    return alpha;
};

console.log(convertToAlpha(str));
console.log(convertToAlpha(str2));

Output

And the output in the console will be ?

lcde
ghief

How It Works

The function processes each digit and checks if combining it with the next digit creates a valid alphabet mapping (10-26). If valid, it uses the two-digit combination and skips the next iteration. Otherwise, it converts the single digit.

For '12345': 12?'l', 3?'c', 4?'d', 5?'e' = 'lcde'

For '78956': 7?'g', 8?'h', 9?'i', 5?'e', 6?'f' = 'ghief'

Conclusion

This approach prioritizes two-digit combinations when they represent valid alphabet mappings (10-26), providing an efficient solution for converting numeric strings to alphabetic representations.

Updated on: 2026-03-15T23:19:00+05:30

914 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements