絵文字をエンコードする方法
絵文字をさまざまな形式(UTF-8 バイト、Unicode エスケープ、HTML エンティティ、Base64)で表現します。
问题
JSON API やレガシーデータベースなど、生の非 ASCII 文字を受け付けないシステムに絵文字を含める必要があります。
前提条件
- Unicode コードポイントの理解
- サロゲートペアへの習熟
ステップ
-
1. Find the emoji code point
Look up the emoji in the Unicode character database. Most emoji are in the U+1F300 to U+1FAFF range. Some emoji use variation selectors (U+FE0F) to request color rendering. Note the full sequence including any selectors.
入力🎉输出U+1F389 -
2. Choose the target format
For JavaScript, use \u{1F389} or the surrogate pair \uD83C\uDF89. For HTML, use 🎉 or the named entity if available. For UTF-8, encode as F0 9F 8E 89. For JSON, the raw emoji is valid if the JSON is UTF-8.
入力🎉输出JS: \uD83C\uDF89 | HTML: 🎉 | UTF-8: F0 9F 8E 89 -
3. Test round-trip fidelity
Decode the representation back to the emoji and verify it renders identically. Some systems strip variation selectors, changing the appearance. Test on multiple platforms if the emoji must render consistently.
入力\uD83C\uDF89输出🎉 ✓
期待される結果
対象プラットフォームで元の文字に正確にデコードされる、絵文字のエンコード表現。
よくあるエラー
- Emoji renders as a monochrome glyph instead of color
- Append the variation selector U+FE0F to request emoji-style (color) rendering on platforms that support it.
- Surrogate pair is split during string manipulation
- Use code-point-aware string operations. Never split a string at an arbitrary index without checking for surrogate boundaries.
トラブルシューティング指引
- If the emoji shows as a box, the target system lacks a font with that glyph. This is a rendering issue, not an encoding error.
- Zwj sequences (zero-width joiner) create compound emoji like 👨👩👧. Handle them as a single grapheme cluster.
セキュリティ上の制限
- Emoji can be used in homoglyph or ZWJ-based obfuscation attacks. Normalize and inspect emoji sequences in security-sensitive contexts.