UNPKG

658 BJavaScriptView Raw
1var toString = require('../lang/toString');
2var trim = require('./trim');
3 /**
4 * Limit number of chars.
5 */
6 function truncate(str, maxChars, append, onlyFullWords){
7 str = toString(str);
8 append = append || '...';
9 maxChars = onlyFullWords? maxChars + 1 : maxChars;
10
11 str = trim(str);
12 if(str.length <= maxChars){
13 return str;
14 }
15 str = str.substr(0, maxChars - append.length);
16 //crop at last space or remove trailing whitespace
17 str = onlyFullWords? str.substr(0, str.lastIndexOf(' ')) : trim(str);
18 return str + append;
19 }
20 module.exports = truncate;
21