22

I'm trying to convert numbers into letters. I'm making an array of divs that either need a number or a number and letter. so 1-3 are just 1-3. but 4-13 need to be a/4, b/5, c6 and so on. is there a way I can converts these numbers into letter easily. maybe changing the ascii values by a set amount?

     for(var i = 1; i < 33; i++){
    if( i < 4 || (i > 13 && i < 20) || i > 29){
        $('#teeth-diagram').append("<div class='tooth' id='" + i + "'>&nbsp;</div>");
    }else{
        $('#teeth-diagram').append("<div class='tooth' id='" + Letter goes here + "/" + i + "'>&nbsp;</div>");
    }
}
Gambai
  • 651
  • 1
  • 7
  • 25
  • I think I'm missunderstood. I don't want to type in a, b, c, d on each div. I just want it to be done dynamically. so if I can convert 4 in to a and 5 in to b that would be great – Gambai Nov 02 '12 at 19:47
  • This one should be helpful - [create string or char from an ascii value][1] [1]: http://stackoverflow.com/questions/602020/javascript-create-a-string-or-char-from-an-ascii-value – Ethan B. Martin Nov 02 '12 at 19:49
  • @lserni Not without something like http://jalaj.net/2007/03/08/asc-and-chr-in-javascript/ ...what are `ord` and `chr` in javascript? – Ian Nov 02 '12 at 19:52
  • Sorry @Ian, I have them as shortcuts and often forget they're not standard. I had edited my comment, but too late :-) – LSerni Nov 02 '12 at 19:57

3 Answers3

53

since 97 is the ascii value for 'a', and your value for 'a' is 3, you need to do this to get the value of the integer converted to a character:

if(i>=3){
    String.fromCharCode(94 + i);
}
Fisch
  • 3,775
  • 1
  • 27
  • 38
29

Yes, you can. Use var letter = String.fromCharCode(number); To get a lowercase a, the number would be 97, b would be 98 and so forth. For uppercase A 65, B would be 66 and so forth. See this JSFiddle for an example

Lukas_Skywalker
  • 2,053
  • 1
  • 16
  • 28
6

You can use the String.fromCharCode(x) function for this, you just need to pass the proper index (eg: 97 = a, 98 = b)

const numberA = 1; // 1 = A, 2 = B,...., 26 = Z
const numberB = 2; 


//lowercase (start in CharCode 97)
console.log( String.fromCharCode(96 + numberA) ); //a
console.log( String.fromCharCode(96 + numberB) ); //b
   

console.log("------------");


//uppercase (start in CharCode 65)
console.log( String.fromCharCode(64 + numberA) ); //A
console.log( String.fromCharCode(64 + numberB) ); //B    
Juanma Menendez
  • 17,253
  • 7
  • 59
  • 56
Dheeraj kumar Rao
  • 8,132
  • 3
  • 22
  • 24
  • 2
    For uppercase I would recommend just using the starting point of 64 instead of 96. For me I use this: `//Index is base 0 so I use 65. getLetter(index: number): string { // String.fromCharCode(65) returns (capital) A. The next 26 chars is the subsequent letter. return String.fromCharCode(65 + index); }` – werdsackjon Sep 30 '21 at 16:00
  • Note: 64 and 96 are NOT alphabet characters. So if you're using base 0, start at 65 and 97 – shieldgenerator7 Jun 20 '23 at 04:04