Created
January 19, 2022 10:13
-
-
Save salvoravida/e0d6cb47b87e34f854b6807b76005528 to your computer and use it in GitHub Desktop.
unescape unicode and utf-8 hex chars
This file contains hidden or 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
/** | |
* \xe2\x98\x89 Mercury -> β Mercury | |
**/ | |
function unescapeUtf8Hex(s: string): string { | |
if (typeof s !== 'string') return s; | |
return s.replace(/(?:\\x[\da-fA-F]{2})+/g, (m) => decodeURIComponent(m.replace(/\\x/g, '%'))); | |
} | |
/** | |
* \\\\U0001F528 hello \\U0001F528 hello -> π¨ hello π¨ hello | |
**/ | |
function unescapeUnicode(s: string): string { | |
if (typeof s !== 'string') return s; | |
return s.replace(/\\\\u[0-9A-Fa-f]*|\\u[0-9A-Fa-f]*/gi, (s) => { | |
const escaped = s.replace(/\\\\u/i, '\\u'); | |
const codePoint = escaped.replace(/\\u/i, '0x'); | |
try { | |
return String.fromCodePoint(Number(codePoint)); | |
} catch (e) { | |
return s; | |
} | |
}); | |
} | |
export function unescapeAll(s: string): string { | |
return unescapeUnicode(unescapeUtf8Hex(s)); | |
} |
Author
salvoravida
commented
Jan 19, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment