forked from esamattis/underscore.string
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prune.js
27 lines (22 loc) · 904 Bytes
/
prune.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
/**
* _s.prune: a more elegant version of truncate
* prune extra chars, never leaving a half-chopped word.
* @author github.com/rwz
*/
var makeString = require('./helper/makeString');
var rtrim = require('./rtrim');
module.exports = function prune(str, length, pruneStr) {
str = makeString(str);
length = ~~length;
pruneStr = pruneStr != null ? String(pruneStr) : '...';
if (str.length <= length) return str;
var tmpl = function(c) {
return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' ';
},
template = str.slice(0, length + 1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
if (template.slice(template.length - 2).match(/\w\w/))
template = template.replace(/\s*\S+$/, '');
else
template = rtrim(template.slice(0, template.length - 1));
return (template + pruneStr).length > str.length ? str : str.slice(0, template.length) + pruneStr;
};