Skip to content

Instantly share code, notes, and snippets.

@kawanet
Last active January 5, 2021 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kawanet/664fac295668478b38402f5c09655f34 to your computer and use it in GitHub Desktop.
Save kawanet/664fac295668478b38402f5c09655f34 to your computer and use it in GitHub Desktop.
絵文字(Unicode サロゲートペア)をエスケープする関数
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