Code Lab

Truncate a string

EasyStrings5 min

Write a function truncate(text, maxLength). If the string is longer than maxLength, cut it and put one … character at the end, so the result is exactly maxLength long. A string that fits in maxLength comes back unchanged.

Examples

truncate('Automation testing', 10)

Returns 'Automatio…'

Nine letters and the ellipsis, 10 characters in total.
truncate('Hello', 5)

Returns 'Hello'

The length is exactly 5, nothing to cut.
truncate('Hello!', 5)

Returns 'Hell…'

Source

Loading the editor...
  1. Inputtruncate('Automation testing', 10)
    Expected'Automatio…'
  2. Inputtruncate('Hello', 5)
    Expected'Hello'
  3. Inputtruncate('Hello!', 5)
    Expected'Hell…'

Hidden tests run on Submit.