Skip to content

Instantly share code, notes, and snippets.

@josephrocca
Created June 18, 2020 11:18
Show Gist options
  • Save josephrocca/884cb04e8557e8368a84b8288239a66b to your computer and use it in GitHub Desktop.
Save josephrocca/884cb04e8557e8368a84b8288239a66b to your computer and use it in GitHub Desktop.
Replace all Unicode characters with escape codes (JavaScript function)
// 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