1

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?

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. 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". Commented Jan 18, 2012 at 18:58
  • No need to mask your JavaScript block: <!-- --> Commented Jan 18, 2012 at 18:58
  • 2
    A good practice - ending each statement with a semicolon. Commented Jan 18, 2012 at 18:58
  • well now i initialized unicode to 0 but it shows just the unicode of the last character Commented Jan 18, 2012 at 19:08

3 Answers 3

4

JavaScript uses UCS-2 internally.

This means that supplementary Unicode symbols are exposed as two separate code units (the surrogate halves). For example, '𝌆'.length == 2, even though it’s only one Unicode character.

Because of this, if you want to get the Unicode code point for every character in a string, you’ll need to convert the UCS-2 string into an array of UTF-16 code points (where each surrogate pair forms a single code point). You could use Punycode.js’s utility functions for this:

punycode.ucs2.decode('abc'); // [97, 98, 99]
punycode.ucs2.decode('𝌆'); // [119558]
Sign up to request clarification or add additional context in comments.

Comments

2

You should initialize the unicode variable to something, or you're adding the char codes to undefined.

Comments

1

NaN = Not a Number

You need to initialize "unicode" as a numeric type:

var unicode = 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.