Last active
January 5, 2021 08:25
-
-
Save kawanet/664fac295668478b38402f5c09655f34 to your computer and use it in GitHub Desktop.
絵文字(Unicode サロゲートペア)をエスケープする関数
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
const esc = str => str.replace(/(\\)|[\ud800-\udfff]/g, (m, c) => c ? ('\\' + c) : ("\\u" + m.charCodeAt(0).toString(16))); | |
esc('\\') === '\\\\'; | |
'🍺' === '\ud83c\udf7a'; | |
esc('🍺') === '\\ud83c\\udf7a'; | |
JSON.parse(esc('"\\"')) === '\\'; | |
JSON.parse(esc('"🍺"')) === '🍺'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment