DEV Community

Discussion on: 20 JavaScript One-Liners That Will Help You Code Like a Pro

Collapse
 
johandalabacka profile image
Johan Dahl

15 and 16 doesn't work with multi character emojis

> truncateString('Hello 😀 How are you?', 10)
'Hello �...'
Enter fullscreen mode Exit fullscreen mode

You could use Array.from first to convert the string into an array of strings each holding a single character

const truncateString = (string, length) => {
  const chars = Array.from(string)
  return chars.length < length ? string : `${chars.slice(0, length - 3).join('')}...`;
};
Enter fullscreen mode Exit fullscreen mode

This will work correctly

> truncateString('Hello 😀 How are you?', 10)
'Hello 😀...'
Enter fullscreen mode Exit fullscreen mode