Encode String to HEX
I solved it by downloading utf8.js
https://github.com/mathiasbynens/utf8.js
then using the String2Hex
function from above:
alert(String2Hex(utf8.encode('守护村子')));
It gives me the output I want:
e5ae88e68aa4e69d91e5ad90
As a self-contained solution in functional style, you can encode with:
plain.split("")
.map(c => c.charCodeAt(0).toString(16).padStart(2, "0"))
.join("");
The split
on an empty string produces an array with one character (or rather, one UTF-16 codepoint) in each element. Then we can map each to a HEX string of the character code.
Then to decode:
hex.split(/(\w\w)/g)
.filter(p => !!p)
.map(c => String.fromCharCode(parseInt(c, 16)))
.join("")
This time the regex passed to split
captures groups of two characters, but this form of split
will intersperse them with empty strings (the stuff "between" the captured groups, which is nothing!). So filter
is used to remove the empty strings. Then map
decodes each character.
This should work.
var str="some random string";
var result = "";
for (i=0; i<str.length; i++) {
hex = str.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
On Node.js, you can do:
const myString = "This is my string to be encoded/decoded";
const encoded = Buffer.from(myString).toString('hex'); // encoded == 54686973206973206d7920737472696e6720746f20626520656e636f6465642f6465636f646564
const decoded = Buffer.from(encoded, 'hex').toString(); // decoded == "This is my string to be encoded/decoded"