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

Converting text to Unicode in javascript - Stack Overflow

programmeradmin1浏览0评论

I have the following:

function showUnicode()
{
  var text = prompt( 'Enter the wanted text', 'Unicode' ),
      unicode = 0,
      ntext,
      temp,
      i = 0
  ;

  // got the text now transform it in unicode
  for(i; i < text.length; i++)
  {
    unicode += text.charCodeAt(i)

  }

  // now do an alert
  alert( 'Here is the unicode:\n' + unicode + '\nof:\n' + text )

}

Thanks for the idea to initialize unicode but now unicode variable gets the Unicode of the last character, why does it?

I have the following:

function showUnicode()
{
  var text = prompt( 'Enter the wanted text', 'Unicode' ),
      unicode = 0,
      ntext,
      temp,
      i = 0
  ;

  // got the text now transform it in unicode
  for(i; i < text.length; i++)
  {
    unicode += text.charCodeAt(i)

  }

  // now do an alert
  alert( 'Here is the unicode:\n' + unicode + '\nof:\n' + text )

}

Thanks for the idea to initialize unicode but now unicode variable gets the Unicode of the last character, why does it?

Share Improve this question edited Jan 18, 2012 at 19:13 Andrew asked Jan 18, 2012 at 18:54 AndrewAndrew 1654 silver badges16 bronze badges 7
  • 2 unicode is not initialized, so it is undefined. In the first iteration, you are basically doing undefined + someNumber and undefined is converted to NaN. – Felix Kling Commented Jan 18, 2012 at 18:57
  • charCodeAt returns an integer repsenting the unicode codepoint value. If you add them up as you are, you'll be getting back the equivalent of "1+2+3=6", not "123". – Marc B Commented Jan 18, 2012 at 18:58
  • No need to mask your JavaScript block: <!-- --> – Diodeus - James MacFarlane Commented Jan 18, 2012 at 18:58
  • 2 A good practice - ending each statement with a semicolon. – Grace Huang Commented Jan 18, 2012 at 18:58
  • well now i initialized unicode to 0 but it shows just the unicode of the last character – Andrew Commented Jan 18, 2012 at 19:08
 |  Show 2 more ments

3 Answers 3

Reset to default 4

JavaScript uses UCS-2 internally.

This means that supplementary Unicode symbols are exposed as two separate code units (the surrogate halves). For example, '

发布评论

评论列表(0)

  1. 暂无评论