Reputation: 1171
I like the function String.prototype.charCodeAt
, but as it is a method on String
you have to provide an index argument. I know that Ecmascript don't handle individual characters, but is there any "native" way to get a charCode directly from one character? Something like str[0].charCode()
or anything that consider a 1-length string?
Upvotes: 7
Views: 11721
Reputation: 27460
You should define first what does it mean charCode in your case.
JS uses UTF-16 encoded strings so charCodeAt
is a value of UTF-16 code unit at that position. Initially JS used UCS2 subset to which charCodeAt()
had perfect sense. Not anymore with full UCS4 support encoded as UTF-16.
The only method to get real UNICODE code points (is it that charCode of yours?) from string is to use ES6 and its string enumeration feature:
for (let ch of str) { ch here is real UNICODE code point }
Note, the above may have less iterations than str.length.
And check String.prototype.codePointAt().
Upvotes: 3
Reputation: 664548
Is there any native way to get a charCode directly from one character?
No. As you say, EcmaScript does not deal with "one character" things specially.
If you need to deal with single characters, you could readily store them as numeric values directly, and convert them to strings only when you have sequences of them.
Something like
str[0].charCode()
Well, it really looks you actually want to use str.charCodeAt(0)
here.
Upvotes: 4
Reputation: 979
String.prototype.charCode = function(){
return this.charCodeAt(0).toString(16);
}
then you can do
str[0].charCode();
Upvotes: 0