Converting numbers into corresponding alphabets and characters using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers in string format. Our function must return a string. The numbers correspond to the letters of the alphabet in reverse order: a=26, z=1 etc.

We should also account for '!', '?' and ' ' that are represented by '27', '28' and '29' respectively.

Example

Following is the code −

 Live Demo

const arr = ['5', '23', '2', '1', '13', '18', '6'];
const convertToString = (arr) => {
   let res = '';
   for (let char of arr) {
      if (Number(char) <= 26) {
         res += String.fromCharCode(123 - char);
      } else {
         if (char === '27') res += '!';
            else if(char === '28') res += '?'
         else res += ' ';
      };
   };
   return res;
};
console.log(convertToString(arr));

Output

vdyzniu

Updated on: 19-Apr-2021

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements