Convert text to Unicode in javascript

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 of ​​initializing unicode, but now the unicode variable gets Unicode of the last character, why?

+1
source share
3 answers

JavaScript uses UCS-2 internally.

This means that additional Unicode characters are displayed as two separate blocks of code (surrogate halves). For example, 'πŒ†'.length == 2 , although its only Unicode character.

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

 punycode.ucs2.decode('abc'); // [97, 98, 99] punycode.ucs2.decode('πŒ†'); // [119558] 
+3
source

You must initialize the unicode variable with something or add char codes to undefined .

+2
source

NaN = not number

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

 var unicode = 0 
+1
source

All Articles