How To Reverse String.fromcharcode?
String.fromCharCode(72) gives H. How to get number 72 from char H?
Solution 1:
'H'.charCodeAt(0)
Solution 2:
Use charCodeAt:
var str = 'H';
var charcode = str.charCodeAt(0);
Solution 3:
@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);
}
returnparseInt(result, 16);
}
Using it:
utf16ToDig('š°').toString(16)
-> "d800df30"
(Inspiration from https://mothereff.in/utf-8)
Solution 4:
You can define your own global functions like this:
functionCHR(ord)
{
returnString.fromCharCode(ord);
}
functionORD(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.)
Solution 5:
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)],
[]
)
Post a Comment for "How To Reverse String.fromcharcode?"