UNPKG

991 BJavaScriptView Raw
1"use strict";
2function truncate(str, options = {}) {
3 if (typeof str !== 'string')
4 throw new TypeError('str must be a string!');
5 const length = options.length || 30;
6 const omission = options.omission || '...';
7 const { separator } = options;
8 const omissionLength = omission.length;
9 if (str.length < length)
10 return str;
11 if (separator) {
12 const words = str.split(separator);
13 let result = '';
14 let resultLength = 0;
15 for (const word of words) {
16 if (resultLength + word.length + omissionLength < length) {
17 result += word + separator;
18 resultLength = result.length;
19 }
20 else {
21 return result.substring(0, resultLength - 1) + omission;
22 }
23 }
24 }
25 else {
26 return str.substring(0, length - omissionLength) + omission;
27 }
28}
29module.exports = truncate;
30//# sourceMappingURL=truncate.js.map
\No newline at end of file