Scriptdrill

Level 3: Strings and dates Exercise 20 of 45 Pro

Truncate with an ellipsis

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

If `s` has at most `max` characters, return it unchanged. Otherwise keep the first `max - 1` characters and add the ellipsis character `"…"`, so the result is exactly `max` characters long. Count characters as Unicode code points, so a character outside the Basic Multilingual Plane, such as 𝒳, is never cut in half. `max` is at least 1.

What this exercise teaches

Array.from iterates the string by code point, so characters stored as two UTF-16 units stay whole. The length check and the slice both use that array, then join puts the kept characters back together.

A hint if you get stuck

`Array.from(s)` splits a string into code points, unlike `s.length` and `s.slice`, which count UTF-16 units.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Strings and dates