JavaScript: Truncate text to a certain number of characters

How to truncate a text in JavaScript if it is longer than a specified number of characters.

René Kulik on 25.02.2018

Very easy solution to truncate a text in JavaScript if it is longer than a specified number of characters.

let text = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing
elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et
accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet.';

// Up to 50 characters are allowed
const maxCharacters = 50;

// Split the text after each character
const characters = text.split('');

// Slice the text if it has more than 50 characters
if (characters.length > maxCharacters) {
    text = characters.slice(0, maxCharacters).join('') + '...';
}

// Lorem ipsum dolor sit amet, consetetur sadipscing ...
console.log(text);