2 * _s.prune: a more elegant version of truncate
3 * prune extra chars, never leaving a half-chopped word.
4 * @author github.com/rwz
6 var makeString = require('./helper/makeString');
7 var rtrim = require('./rtrim');
9 module.exports = function prune(str, length, pruneStr) {
10 str = makeString(str);
12 pruneStr = pruneStr != null ? String(pruneStr) : '...';
14 if (str.length <= length) return str;
16 var tmpl = function(c) {
17 return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' ';
19 template = str.slice(0, length + 1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
21 if (template.slice(template.length - 2).match(/\w\w/))
22 template = template.replace(/\s*\S+$/, '');
24 template = rtrim(template.slice(0, template.length - 1));
26 return (template + pruneStr).length > str.length ? str : str.slice(0, template.length) + pruneStr;