Stefan Surkamp
Stefan Surkamp

Reputation: 992

Convert Number to Unicode sign

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.

Upvotes: 8

Views: 8236

Answers (3)

Carson
Carson

Reputation: 7978

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

Upvotes: 1

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.

Upvotes: 3

TJHeuvel
TJHeuvel

Reputation: 12608

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

Upvotes: 13

Related Questions