If want to convert a number to its corresponding alphabet letter like this:-
1 = A
2 = B
3 = C
You will need to write a loop, and mod (%) the number by 26 each time through and use the following:
String.fromCharCode(num + 64);
Convert a number to a letter of the alphabet JavaScript example
HTML example code:
Simply do this without arrays using String.fromCharCode(code)
function as letters has consecutive codes. For example: String.fromCharCode(1+64)
gives you ‘A’, String.fromCharCode(2+64)
gives you ‘B’, and so on
<!DOCTYPE html>
<html>
<body>
<script>
function getLetter(num){
var letter = String.fromCharCode(num + 64);
return letter;
}
console.log(getLetter(1));
console.log(getLetter(2));
console.log(getLetter(26));
</script>
</body>
</html>
Output:
Another example with a different method
<script>
var value = 1;
document.write((value + 9).toString(36).toUpperCase());
</script>
One more 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));
Q: How to Convert numbers to letters beyond the 26-character alphabet?
Answer: Generate a number as a letter.
<!DOCTYPE html>
<html>
<body>
<script>
function colName(n) {
var ordA = 'a'.charCodeAt(0);
var ordZ = 'z'.charCodeAt(0);
var len = ordZ - ordA + 1;
var s = "";
while(n >= 0) {
s = String.fromCharCode(n % len + ordA) + s;
n = Math.floor(n / len) - 1;
}
return s;
}
document.write(colName(27));
</script>
</body>
</html>
Output: ab
Do comment if you have any doubts or suggestions on this JS Code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version