Truncate a string to a specific width in the terminal

Overview

cli-truncate

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

const cliTruncate = require('cli-truncate');

cliTruncate('unicorn', 4);
//=> 'uni…'

// Truncate at different positions
cliTruncate('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…'

// Truncate Unicode surrogate pairs
cliTruncate('uni\uD83C\uDE00corn', 5);
//=> 'uni\uD83C\uDE00…'

// Truncate fullwidth characters
cliTruncate('안녕하세요', 3);
//=> '안…'

// Truncate the paragraph to the terminal width
const paragraph = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.';
cliTruncate(paragraph, process.stdout.columns));
//=> 'Lorem ipsum dolor sit amet, consectetuer adipiscing…'

API

cliTruncate(text, columns, options?)

text

Type: string

Text to truncate.

columns

Type: number

Columns to occupy in the terminal.

options

Type: object

position

Type: string
Default: 'end'
Values: 'start' 'middle' 'end'

Position to truncate the string.

space

Type: boolean
Default: false

Add a space between the text and the ellipsis.

cliTruncate('unicorns', 5, {space: false});
//=> 'unic…'

cliTruncate('unicorns', 5, {space: true});
//=> 'uni …'

cliTruncate('unicorns', 6, {position: 'start', space: true});
//=> '… orns'

cliTruncate('unicorns', 7, {position: 'middle', space: true});
//=> 'uni … s'
preferTruncationOnSpace

Type: boolean
Default: false

Truncate the string from a whitespace if it is within 3 characters from the actual breaking point.

cliTruncate('unicorns rainbow dragons', 20, {position: 'start', preferTruncationOnSpace: true})
//=> '…rainbow dragons'

// without preferTruncationOnSpace
cliTruncate('unicorns rainbow dragons', 20, {position: 'start'})
//=> '…rns rainbow dragons'

cliTruncate('unicorns rainbow dragons', 20, {position: 'middle', preferTruncationOnSpace: true})
//=> 'unicorns…dragons'

cliTruncate('unicorns rainbow dragons', 6, {position: 'end', preferTruncationOnSpace: true})
//=> 'unico…'

// preferTruncationOnSpace would have no effect if space isn't found within next 3 indexes
cliTruncate('unicorns rainbow dragons', 6, {position: 'middle', preferTruncationOnSpace: true})
//=> 'uni…ns'

Related

  • wrap-ansi - Wordwrap a string with ANSI escape codes
  • slice-ansi - Slice a string with ANSI escape codes

Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
Comments
  • Add option to add a space either side of ellipsis

    Add option to add a space either side of ellipsis

    Issuehunt badges

    An option to add a space either side of the ellipsis would be nice. thanks

    satyarohith earned $30.00 by resolving this issue!

    enhancement help wanted :gift: Rewarded on Issuehunt 
    opened by danday74 7
  • Option to choose where to truncate

    Option to choose where to truncate

    Currently it's truncated at the end, but an option could enable truncating at the start or in the middle.

    Not something I need right now, but might be useful in the future.

    A good pull request would be much welcome :)

    enhancement help wanted 
    opened by sindresorhus 5
  • Must use import to load ES Module

    Must use import to load ES Module

    Hello,

    I just installed this package, which by the way, seems to be the only one that does truncation and is currently maintained.

    However, I have an issue while using this package inside my Next.Js application (in Typescript).

    Here is how I import the package :

    import cliTruncate from "cli-truncate";
    // I also tried
    import * as cliTruncate from "cli-truncate";
    

    And here is the error on runtime:

    Error: Must use import to load ES Module: D:\workspace\my-app\node_modules\cli-truncate\index.js
    require() of ES modules is not supported.
    require() of D:\workspace\my-app\node_modules\cli-truncate\index.js from D:\workspace\my-app\packages\website\.next\server\pages\blog.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
    Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from D:\workspace\my-app\node_modules\cli-truncate\package.json.
    

    Do you have any idea why is this happening?

    opened by IzioDev 4
  • Add `truncationCharacter` option

    Add `truncationCharacter` option

    This PR adds an option ellipsis that allows the user to replace the default with another character.

    Example:

    import cliTruncate from 'cli-truncate';
    
    // Without option
    cliTruncate('unicorns', 5, {position: 'end'});
    //=> 'unic…'
    
    // With option set to '.'
    cliTruncate('unicorns', 5, {position: 'end', ellipsis: '.'});
    //=> 'unic.'
    
    // With option set to ''
    cliTruncate('unicorns', 5, {position: "end", ellipsis: ''});
    //=> 'unico'
    

    Includes type definitions and documentation.


    Closes #18

    opened by codemaster138 3
  • Add `preferTruncationOnSpace` option

    Add `preferTruncationOnSpace` option

    just finding a space within next 3 characters form actual breeaking point. If the string has to be truncated from start then it searches towards left and if the string has to be truncated from end then it searched towards right, so that the length of the truncated string is not more than the columns argument passed.

    some changes to the code were done by xo --fix (xo asked for them) like doing destructuring.

    Fixes #8

    opened by ammarbinfaisal 3
  • Support fullwidth characters and unicode surrogate pairs

    Support fullwidth characters and unicode surrogate pairs

    https://github.com/sindresorhus/cli-truncate/blob/dbc522d6f3c1fd7b287b39521ed73a7c9e98fd66/test.js#L15-L17

    Depends on https://github.com/chalk/wrap-ansi/issues/10 and https://github.com/chalk/wrap-ansi/issues/11.

    Note to self: Update the readme description when this is fixed.

    enhancement help wanted 
    opened by sindresorhus 3
  • Remove object rest operator to support Node.js 8

    Remove object rest operator to support Node.js 8

    Object rest operator was introduced in ES2018, and was not fully supported in Node.js 8 until 8.6.0: https://node.green/#ES2018-features-object-rest-spread-properties

    Hope we can keep compatibility with all the Node.js 8 version. We can revert this commit when we drop support of Node.js 8.

    opened by bet4it 2
  • Add option to prefer truncating on spaces if possible

    Add option to prefer truncating on spaces if possible

    Issuehunt badges

    See: https://github.com/sindresorhus/fkill-cli/pull/47#issuecomment-375361462


    IssueHunt Summary

    ammarbinfaisal ammarbinfaisal has been rewarded.

    Sponsors (Total: $40.00)

    Tips

    enhancement help wanted :gift: Rewarded on Issuehunt 
    opened by sindresorhus 2
  • Ellipsis color is always white

    Ellipsis color is always white

    Hi,

    in cliTruncate( chalk.gray( someLongFileName ), process.stdout.columns, { position: 'middle' } ) the ellipsis color is white (not gray).

    Better having a color property in the options, like { position: 'middle', color: 'gray' } ?

    Note: tested only on Win10

    opened by thiagodp 1
  • Transpiling ES6 to ES5 on fixing Safari "const" ">

    Transpiling ES6 to ES5 on "prepublish" -> fixing Safari "const"

    Current library uses ES6 code in main output file. Safari 10.11.* (El Captain) does not support ES6 "const" in "strict mode" (as well as arrow functions). Original console error message: "Const declarations are not supported in strict mode".

    On "prepublish" command I suggest transpile all ES6 code (include node_modules) to ES5, minify and make ES5 /lib/bundle.js as a main library file (for NPM). In github ES6 source code will be available in /src folder.

    opened by thgala 1
  • Use other character (or no character) instead of elipsis

    Use other character (or no character) instead of elipsis

    This is a great tool, but the one thing preventing me from using it the fact that in my use case i'd like the text to be truncated w/o an ellipsis.

    Could we have an option truncateChar or so that allows us replace the ellipsis with another character (or none at all)?

    opened by codemaster138 0
  • Truncates more characters than necessary

    Truncates more characters than necessary

    Reproduction from the readme:

    cliTruncate('unicorn', 4);
    //=> 'un…', not 'uni…'
    

    Can be reproduced without any changes by pulling a fresh clone of this repository and running npm test.

    ❯ npm t
    
    > [email protected] test
    > xo && ava && tsd
    
    
      main
    
      Difference:
    
      - 'un…'
      + 'uni…'
    
      › file://test.js:5:4
    
    
    
      space option
    
      Difference:
    
      - 'un …'
      + 'uni …'
    
      › file://test.js:25:4
    
      ─
    
      2 tests failed
    

    I reverted https://github.com/sindresorhus/cli-truncate/commit/23b40dc576d53f83a88caa2001ce5341d9f3241c locally and tests are passing now, so it has to be a regression from https://github.com/sindresorhus/cli-truncate/pull/19. cc @codemaster138

    opened by vadimdemedes 1
  • Automatic style detection

    Automatic style detection

    It'd be cool, although probably a bit unnecessary and overcomplicated, if for example when truncating at the end the style of the character preceding the ellipses is detected and the ellipsis is written using the same style.

    enhancement help wanted 
    opened by fabiospampinato 3
Releases(v3.1.0)
Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
Terminal ui for discord with interactive terminal

dickord why No fucking clue i was bored or something. why does it look dogshit Try and find a node module that supports terminal functions like trauma

Hima 3 Nov 7, 2022
An extension geared towards Spotify users with larger libraries; view all your playlists that contain a specific song with the click of a button. Designed for Spicetify (https://github.com/khanhas/spicetify-cli)

ViewPlaylistsWithSong An extension developed for Spicetify that allows you to view all the playlists in your library that contain a certain song. Idea

null 21 Dec 13, 2022
Sublime-like terminal-based text editor

slap ?? slap is a Sublime-like terminal-based text editor that strives to make editing from the terminal easier. It has: first-class mouse support (ev

slap 6.1k Jan 1, 2023
A terminal-to-gif recorder minus the headaches.

ttystudio A terminal-to-gif recorder minus the headaches. Record your terminal and compile it to a GIF or APNG without any external dependencies, bash

Christopher Jeffrey (JJ) 3.2k Dec 23, 2022
rtail(1) - Terminal output to the browser in seconds, using UNIX pipes.

rtail(1) Terminal output to the browser in seconds, using UNIX pipes. rtail is a command line utility that grabs every line in stdin and broadcasts it

Kilian Ciuffolo 1.6k Jan 6, 2023
Pipeable javascript. Quickly filter, map, and reduce from the terminal

Pipeable JavaScript - another utility like sed/awk/wc... but with JS! Quickly filter, map and reduce from the command line. Features a streaming API.

Daniel St. Jules 410 Dec 10, 2022
Translations with speech synthesis in your terminal as a node package

Normit Normit is an easy way to translate stuff in your terminal. You can check out its Ruby gem version termit. Installation npm install normit -g Us

Paweł Urbanek 234 Jan 1, 2023
Terminal recorder: Record your termial session into HTML

terminal-recorder Terminal recorder allows you to record your bash session, and export it to html so then you can share it with your friends. GitHub P

Cristian Cortez 104 Mar 3, 2022
Terminal task list

listr Terminal task list Install $ npm install --save listr Usage const execa = require('execa'); const Listr = require('listr'); const tasks = new

Sam Verschueren 3.1k Jan 3, 2023
📜 Create mutable log lines into the terminal, and give life to your logs!

Because Logging can be pretty and fun Installation $ npm install draftlog What it does It allows you to re-write a line of your log after being writt

Ivan Seidel 1.2k Dec 31, 2022
Display images in the terminal

terminal-image Display images in the terminal Works in any terminal that supports colors. In iTerm, the image will be displayed in full resolution, si

Sindre Sorhus 905 Dec 25, 2022
:rainbow: Beautiful color gradients in terminal output

gradient-string Beautiful color gradients in terminal output Install $ npm i gradient-string Usage const gradient = require('gradient-string'); cons

Boris K 864 Jan 3, 2023
Create clickable links in the terminal

terminal-link Create clickable links in the terminal Install $ npm install terminal-link Usage import terminalLink from 'terminal-link'; const link

Sindre Sorhus 539 Dec 31, 2022
Reliably get the terminal window size

term-size Reliably get the terminal window size Because process.stdout.columns doesn't exist when run non-interactively, for example, in a child proce

Sindre Sorhus 132 Oct 11, 2022
Execute shell commands in terminal

Execute shell commands in terminal

skanehira 9 Dec 11, 2021
Add a hungry turtle to your terminal and feed it every time you mistype 'npm' as 'nom'

Nom Does this ever happen to you? You happily code away on a project, navigating the command line like a pro, testing, error logging, installing packa

Meike Hankewicz 5 Apr 26, 2022
Just a minimal library to do some terminal stuff.

Termctl A simple library to do some basic terminal stuff. Usage const termctl = require("termctl"); Note: We have tested this on Linux Mint and Window

Biraj 4 Sep 28, 2021
A terminal for a more modern age

Downloads: Latest release Repositories: Debian/Ubuntu-based, RPM-based Latest nightly build This README is also available in: Korean 简体中文 Tabby (forme

null 41.8k Dec 30, 2022