Truncate a string to a specific width in the terminal
Gracefully handles ANSI escapes. Like a string styled with chalk. It also supports Unicode surrogate pairs and fullwidth characters.
Install
npm install cli-truncate
Usage
import cliTruncate from 'cli-truncate';cliTruncate('unicorn', 4);//=> 'uni…'// Truncate at different positionscliTruncate('unicorn', 4, {position: 'start'});//=> '…orn'cliTruncate('unicorn', 4, {position: 'middle'});//=> 'un…n'cliTruncate('unicorns rainbow dragons', 6, {position: 'end'});//=> 'unico…'cliTruncate('\u001B[31municorn\u001B[39m', 4);//=> '\u001B[31muni…\u001B[39m'
[!NOTE]
When truncating styled text (ANSI escapes), the truncation character inherits the style at the breaking point for position: 'start' and position: 'end'. This does not apply to position: 'middle'.
API
cliTruncate(text, columns, options?)
text
Type: string
The text to truncate.
columns
Type: number
The finite number of columns to occupy in the terminal.