6

I have to print out the letters from A to Z each for itself. So I tried the following:

for(var i = 65; i < 91; i++) {
     $('#alphabet').append('<div class="letter">' + '%' + i + '</div>');
}

My idea is to use the decimal numbers of the letters (for example: 65 - A) to easily print them via loop. Is this possible or do I have to use an array?

Best regards.

3 Answers 3

11

You can use String.fromCharCode to convert a character code to string.

4
  • thats exactly what i've been looking for (hours). thank you very much! Commented Nov 1, 2011 at 11:08
  • @Josh Why write the name of Stefan Surkamp in Russian when he/she appears to be a German? Also "Ш" appears to imitate the pronounciation in Deutsche, quite interesting. :)
    – awllower
    Commented Jan 11, 2015 at 9:43
  • I'm sure I used autocomplete @awllower. I bet he's changed his display name ;-)
    – Josh
    Commented Jan 11, 2015 at 14:21
  • @Josh I found out that there is such a functionality as auto-complete after using the website for 3 years and 11 months (on math stack exchange). Thanks for that information. ;)
    – awllower
    Commented Jan 11, 2015 at 15:49
2

For this use (printing letters from A to Z), String.fromCharCode is sufficient; however, the question title specifies Unicode. If you are looking to convert Unicode codes (and if you came here from search, you might), you need to use String.fromCodePoint.

Note, this function is new to ES6/ES2015, and you may need to use a transpiler or polyfill to use it in older browsers.

0

String.fromCharCode

[...Array(91-65)].map((_, i)=>console.log(String.fromCharCode(i+65)))

String.fromCharCode(...codes: number[]): string A sequence of numbers that are UTF-16 code units.

Therefore, for Unicode code points greater than 0xFFFF, surrogate pairs (U+D800 to U+DFFF (surrogates) are needed to display them.

You can use the following function to achieve this:

function fromCodePoint(codePoint) {
  if (codePoint > 0xFFFF) {
    codePoint -= 0x10000
    // const high = 0xD800 + (codePoint >> 10)
    // const low = 0xDC00 + (codePoint & 0x3FF) // 0x3FF 0011_1111_1111
    // return String.fromCharCode(high, low)
    return String.fromCharCode(
      0xD800 + (codePoint >> 10), 
      0xDC00 + (codePoint & 0x3FF)
    )
  }
  return String.fromCharCode(codePoint)
}

console.log(fromCodePoint(0x4E00))
console.log(fromCodePoint(0x1FA80)) // Yo-Yo // https://www.compart.com/en/unicode/U+1fa80

Not the answer you're looking for? Browse other questions tagged or ask your own question.