Guest User

Untitled

a guest
Mar 13th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. // Port of Kohana3's Text::limit_chars helper
  2.  
  3. String.implement({
  4.  
  5. limitChars: function(limit, options){
  6. var opts = {
  7. endChar: null,
  8. preserveWords: false
  9. };
  10. $extend(opts, options);
  11.  
  12. var endChar = (opts.endChar == null) ? '…' : opts.endChar;
  13. if (this.trim() === '' || this.length <= limit) return this;
  14. if (limit <= 0) return endChar;
  15. if (!opts.preserveWords) return this.substr(0, limit) + endChar;
  16.  
  17. var pattern = new RegExp('^.{' + (limit-1) + '}\\S*');
  18. var matches = this.match(pattern);
  19. return matches[0].trim() + ((matches[0].length == this.length) ? '' : endChar);
  20. }
  21.  
  22. });
Add Comment
Please, Sign In to add comment