Skip to content

Unicode String Slicing Error

Quick summary

You used .slice on a string with emoji or astral characters — the cut lands inside a surrogate pair and produces a broken character.

Why this happens

  • Using String.prototype.slice/substring on strings with astral characters (emoji)

  • Counting 'characters' with .length, which counts UTF-16 code units not glyphs

  • Truncating to N code units when N glyphs was intended

Minimal example

✗ Broken code
const str = 'Hello 🌍!';
console.log(str.slice(0, 7)); // 'Hello �' — surrogate pair split
✓ Fixed code
const str = 'Hello 🌍!';
console.log([...str].slice(0, 7).join('')); // 'Hello 🌍' — whole glyph kept

The emoji 🌍 is two UTF-16 code units, so slice(0,7) cuts between them and yields a broken character. Spreading into an array of code points keeps the glyph intact.

How to diagnose

  • Print the sliced result and look for replacement characters (U+FFFD)

  • Check the string for code points above U+FFFF (emoji, rare symbols)

  • Compare .length with Array.from(str).length to detect surrogate pairs

How to fix

  • Slice by code points: [...str].slice(0, n).join('')

  • Use a library that understands grapheme clusters for complex text

  • Normalize the string with String.prototype.normalize before slicing

How to prevent

  • Operate on arrays of code points ([...str]) for user-visible text

  • Use a grapheme-aware library for truncation and counting

Related Resources

Related Glossary

Related Lessons

  • Strings

    Learn about Unicode and strings.

← Back to language