String.fromCharCode(72) gives H. How to get number 72 from char H?
-
2the code in the question is what I came here for, not the answer. Thanks! – bluejayke Jan 31 '20 at 2:20
'H'.charCodeAt(0)
-
1Hi, thanks for the solution. Will it work only with english words? when I tried to find the char code for a tamil word its not working properly. If I use String.fromCharCode(2974); it returns the character 'ஞ', the same way, If I use 'ஞ'.charCodeAt(0) am getting 38, and that is for '&', why is it so? – shanish Feb 24 '14 at 6:00
-
1@shanish: What do you get if you write
String.fromCharCode(2974).charCodeAt(0)
? (It works for me.) Perhaps your editor and/or source file are not Unicode-friendly. – Lightness Races in Orbit Aug 12 '14 at 16:36
@Silvio's answer is only true for code points up to 0xFFFF (which in the end is the maximum that String.fromCharCode can output). You can't always assume the length of a character is one:
'𐌰'.length
-> 2
Here's something that works:
var utf16ToDig = function(s) {
var length = s.length;
var index = -1;
var result = "";
var hex;
while (++index < length) {
hex = s.charCodeAt(index).toString(16).toUpperCase();
result += ('0000' + hex).slice(-4);
}
return parseInt(result, 16);
}
Using it:
utf16ToDig('𐌰').toString(16)
-> "d800df30"
(Inspiration from https://mothereff.in/utf-8)
You can define your own global functions like this:
function CHR(ord)
{
return String.fromCharCode(ord);
}
function ORD(chr)
{
return chr.charCodeAt(0);
}
Then use them like this:
var mySTR = CHR(72);
or
var myNUM = ORD('H');
(If you want to use them more than once, and/or a lot in your code.)
-
2Please do not use my suggestion any more. I strongly suggest using an object to wrap your functions, instead of definging them globally. – David Refoua Aug 2 '18 at 8:37
String.fromCharCode
accepts multiple arguments, so this is valid:
const binaryArray = [10, 24] // ...
str = String.fromCharCode(...binaryArray)
In case you're looking for the opposite of that (like I was), this might come in handy:
const binaryArray = str
.split('')
.reduce((acc, next) =>
[...acc, next.charCodeAt(0)],
[]
)