#51 · Strings and dates

Find the bug · #51 · Strings and dates Medium JavaScript

Message previews break emojis

Notification previews cut messages short, and sometimes end in a broken character.

On this page

The report

Bug report

Notifications show the first 15 characters of a message. When the cut lands on an emoji, the preview ends in a broken “�” character, and some phones drop the notification entirely.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
// The first n characters of a message, for the notification preview.
function preview(text, n) {
  return text.length <= n ? text : text.slice(0, n) + '…';
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
const msg = 'Party tonight 🎉🎉';
console.log(JSON.stringify(preview(msg, 15)));
console.log(preview(msg, 15).isWellFormed());

It prints

"Party tonight \ud83c…"
false

It should print

"Party tonight 🎉…"
true
Show the answer: the bug, the fix, and how you’d find it

The bug (line 3)

Line 3 measures and cuts the text in UTF-16 code units. Most emojis take two code units (a “surrogate pair”), so "🎉".length is 2, and slice can cut an emoji in half, leaving half a character that shows up as “�”. Work in whole characters: Array.from(text) splits by code point.

The fix

1// The first n characters of a message, for the notification preview.2function preview(text, n) {3  return text.length <= n ? text : text.slice(0, n) + '…';3  const chars = Array.from(text);4  return chars.length <= n ? text : chars.slice(0, n).join('') + '…';4}

How you’d find it

  1. Reproduce with a message where the cut falls on an emoji: the preview ends in a lone \ud83c.
  2. Check lengths: "Party tonight 🎉🎉".length is 18, but it shows 16 characters. Each emoji counts as two.
  3. So slice(0, 15) stops halfway through the first emoji. Cut by code point instead.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

assert.equal(preview('Hi 👋👋👋', 4), 'Hi 👋…');
assert.ok(preview('Hi 👋👋👋', 4).isWellFormed());
assert.equal(preview('short', 10), 'short');

Where else this bites

  • Validating a “max 30 characters” username with .length.
  • Reversing a string with split("").reverse() breaks emojis the same way.
Your progress stays on this device.