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.

Example

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)];
         i++;
      }
      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

Updated on: 21-Nov-2020

613 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements