Skip to content

Instantly share code, notes, and snippets.

@lyquix-owner
Created April 15, 2020 11:43
Show Gist options
  • Save lyquix-owner/181d2bf458bad58d56b30803b4d1fb1b to your computer and use it in GitHub Desktop.
Save lyquix-owner/181d2bf458bad58d56b30803b4d1fb1b to your computer and use it in GitHub Desktop.
JavaScript functions to convert UTF-8 string to hexadecimal string, and back. Correctly handle multi-byte. Demo https://jsfiddle.net/lyquix/k2tjbrvq/
function utf8_hex(str) {
return Array.from(str).map(c =>
c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16).padStart(2, '0') :
encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
).join('');
}
function hex_utf8(hex) {
return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment