最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert Number to Unicode sign - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Nov 1, 2011 at 10:57 Stefan SurkampStefan Surkamp 9921 gold badge16 silver badges31 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

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

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.

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

发布评论

评论列表(0)

  1. 暂无评论