If I have a string, for example: abcℂ
, then how do I escape the non-ASCII characters? Here is the desired behavior:
escapeUnicode("abcℂ") → "abc\ud835\udd38\ud835\udd39\u2102"
If I have a string, for example: abcℂ
, then how do I escape the non-ASCII characters? Here is the desired behavior:
escapeUnicode("abcℂ") → "abc\ud835\udd38\ud835\udd39\u2102"
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 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("");
}