Number to alphabets in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.


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];
      if(+(el + next) <= 26){
         alpha += legend[+(el + next)];
         alpha += legend[+el];
   return alpha;


And the output in the console will be −

Published on 21-Nov-2020 14:28:54