prune.js 908 B

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