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.
# With yarn.
yarn add smart-truncate;
# With npm.
npm install --save smart-truncate;
smartTruncate(string, length[, options])
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 "…".
A new string truncated with an ellipsis or custom mark.
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'
]
npm test
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.