/
truncate.js
70 lines (58 loc) · 1.53 KB
/
truncate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* Truncate a string to a specific width.
*
* |Name |Desc |
* |-------|---------------------|
* |txt |Text to truncate |
* |width |Maximum string length|
* |options|Options object |
* |return |Truncated string |
*
* Options:
*
* |Name |Desc |
* |--------------|----------------------------------|
* |ellipsis='...'|String to indicate text is omitted|
* |separator |Separator pattern to truncate to |
*/
/* example
* truncate('ORA ORA ORA ORA ORA ORA', 12); // -> 'ORA ORA O...'
* truncate('ORA ORA ORA ORA ORA ORA', 10, {
* separator: ' ',
* ellipsis: '……'
* }); // -> 'ORA ORA……'
*/
/* module
* env: all
* since: 1.20.0
*/
/* typescript
* export declare function truncate(
* txt: string,
* width: number,
* options?: {
* ellipsis?: string;
* separator: string;
* }
* ): string;
*/
_('defaults isUndef');
exports = function(txt, width, options = {}) {
defaults(options, defOptions);
const { ellipsis, separator } = options;
const len = txt.length;
if (width > len) return txt;
const end = width - ellipsis.length;
if (end < 1) return ellipsis;
let ret = txt.slice(0, end);
if (isUndef(separator)) return ret + ellipsis;
if (txt.indexOf(separator, end) !== end) {
const idx = ret.lastIndexOf(separator);
if (idx > -1) {
ret = ret.slice(0, idx);
}
}
return ret + ellipsis;
};
const defOptions = {
ellipsis: '...'
};