Skip to content

millerized/smart-truncate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

43 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Smart Truncate npm version Build Status Coverage Status size gzip size

A small library that truncates a string. It can insert or append an ellipsis (or a custom mark) at any desired position of the truncated result.

Installation

# With yarn.
yarn add smart-truncate;

# With npm.
npm install --save smart-truncate;

Syntax

smartTruncate(string, length[, options])

Paramaters

string
 A string with a minimum length of 4 characters.

length
 The length of the truncated result.

options
options.position
 Optional. The index of the ellipsis (zero based). Default is at the end.
options.mark
 Optional. The character[s] indicating omission. Default is an ellipsis "…".

Return value

A new string truncated with an ellipsis or custom mark.

Usage

const smartTruncate = require('smart-truncate');

const string = 'To iterate is human, to recurse divine.';

// Append an ellipsis at the end of the truncated string.
const truncated = smartTruncate(string, 15);

Output: "To iterate is …"


const string = 'To iterate is human, to recurse divine.';

// Insert an ellipsis in the middle of a smart truncated string.
const truncated = smartTruncate(string, 21, {position: 10});

Output: "To iterate…se divine."


const files = [
    '1Password 6.app',
    'Adobe',
    'Adobe Creative Cloud',
    'Adobe Illustrator CC 2015.3',
    'Adobe Photoshop CC 2014',
    'Adobe Photoshop CC 2015.5',
    'App Store.app'
];

const truncated = files.map((filename) => smartTruncate(filename, 21, {position: 10}));

Output:

[
    '1Password 6.app',
    'Adobe',
    'Adobe Creative Cloud',
    'Adobe Illu… CC 2015.3',
    'Adobe Phot…op CC 2014',
    'Adobe Phot… CC 2015.5',
    'App Store.app'
]

Tests

npm test

Contributing

In lieu of a formal style guide, take care to maintain the existing coding style. Add tests for any new or changed functionality. Lint and test your code.