Created
June 18, 2020 11:18
-
-
Save josephrocca/884cb04e8557e8368a84b8288239a66b to your computer and use it in GitHub Desktop.
Replace all Unicode characters with escape codes (JavaScript function)
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
// This function matches all non-ASCII characters after splitting the string in a "unicode-safe" way (using `[...str]`). | |
// It then splits each unicode character up into its code-points, and gets the escape code for each, and then joins all | |
// all the ASCII characters and Unicode escapes into one string. | |
function escapeUnicode(str) { | |
return [...str].map(c => /^[\x00-\x7F]$/.test(c) ? c : c.split("").map(a => "\\u" + a.charCodeAt().toString(16).padStart(4, "0")).join("")).join(""); | |
} | |
// Based on discussion in this thread: https://gist.github.com/mathiasbynens/1243213 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment