Created
April 15, 2020 11:43
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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