5

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"
2
  • Please take time to search for your problem before asking a question. stackoverflow.com/questions/7499473/… Commented Jun 18, 2020 at 11:39
  • 2
    @SamWalpole Ah, you're right. I did try a few Google searches and only found python and PHP variants. I already had the JS answer so I figured I'd make a SO question on it and answer my own question so it was easier for future searchers to find. Also, interesting that SO didn't find that question in the "related questions" box that you get before submitting a question, since the titles are very similar. Commented Jun 19, 2020 at 7:22

1 Answer 1

5

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("");
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.