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 isundefined
. In the first iteration, you are basically doingundefined + someNumber
andundefined
is converted toNaN
. – 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
3 Answers
Reset to default 4JavaScript uses UCS-2 internally.
This means that supplementary Unicode symbols are exposed as two separate code units (the surrogate halves). For example, '