
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Number to Alphabet Letter in JavaScript
We are required to write a function that takes in a number between 1 and 26 (both inclusive) and returns the corresponding English alphabet for it. (capital case) If the number is out of this range return -1.
For example −
toAlpha(3) = C toAlpha(18) = R
And so on.
The ASCII Codes
ASCII codes are the standard numerical representation of all the characters and numbers present on our keyboard and many for.
The capital English alphabets are also mapped in the ascii char codes, they start from 65 and goes all the way up to 90, with 65 being the value for ‘A’, 66 for ‘B’ and so. We can use these codes to map our alphabets
The full code for doing this will be −
Example
const toAlpha = (num) => { if(num < 1 || num > 26 || typeof num !== 'number'){ return -1; } const leveller = 64; //since actually A is represented by 65 and we want to represent it with one return String.fromCharCode(num + leveller); }; console.log(toAlpha(18));
Output
The output in the console will be −
R
Advertisements