Languages
[Edit]
EN

JavaScript - how to convert integer number to letter?

14 points
Created by:
AnnLen
1777

Simple example

// ONLINE-RUNNER:browser;

console.log( String.fromCharCode(97) );  // a
console.log( String.fromCharCode(98) );  // b
console.log( String.fromCharCode(122) ); // z

console.log( String.fromCharCode(65) );  // A
console.log( String.fromCharCode(66) );  // B
console.log( String.fromCharCode(90) );  // Z

1. String.fromCharCode method examples

This approach is used to get existing character by code.

1.1. Small letters example

// ONLINE-RUNNER:browser;

for (var i = 0; i < 26; ++i) {
  	var code = i + 97;
	var letter = String.fromCharCode(code);
  	
  	console.log(code + ' : ' + letter);
}

2.2. Big letters example

// ONLINE-RUNNER:browser;

for (var i = 0; i < 26; ++i) {
  	var code = i + 65;
	var letter = String.fromCharCode(code);
  	
  	console.log(code + ' : ' + letter);
}

2. Custom alphabet example

2.1. Text alphabet example

// ONLINE-RUNNER:browser;

var alphabet = ''
    + 'abcdefghijklmnopqrstuvwxyz' 
	+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

for (var i = 0; i < alphabet.length; ++i) {
  	var code = i;

	var letter = alphabet[code];
	//var letter = alphabet.charAt(code);
  	
  	console.log(code + ' : ' + letter);
}

2.2. Map / dictionary alphabet example

Map helps to assign specific codes for characters.

// ONLINE-RUNNER:browser;

var alphabet = {
     "65": "A",  "66": "B",  "67": "C",  "68": "D",  "69": "E", 
     "70": "F",  "71": "G",  "72": "H",  "73": "I",  "74": "J", 
     "75": "K",  "76": "L",  "77": "M",  "78": "N",  "79": "O", 
     "80": "P",  "81": "Q",  "82": "R",  "83": "S",  "84": "T", 
     "85": "U",  "86": "V",  "87": "W",  "88": "X",  "89": "Y", 
     "90": "Z",

     "97": "a",  "98": "b",  "99": "c", "100": "d", "101": "e", 
    "102": "f", "103": "g", "104": "h", "105": "i", "106": "j", 
    "107": "k", "108": "l", "109": "m", "110": "n", "111": "o", 
    "112": "p", "113": "q", "114": "r", "115": "s", "116": "t", 
    "117": "u", "118": "v", "119": "w", "120": "x", "121": "y", 
    "122": "z"
};

for (var i = 0; i < 128; ++i) {
  	var code = i.toString();

    if (code in alphabet) {
	    var letter = alphabet[code];
  	
  	    console.log(code + ' : ' + letter);
    }
}

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.