Skip to content

Instantly share code, notes, and snippets.

@cheeaun
Created October 8, 2009 06:40
Show Gist options
  • Save cheeaun/204816 to your computer and use it in GitHub Desktop.
Save cheeaun/204816 to your computer and use it in GitHub Desktop.
MooTools String.limitChars with 'preserve words' option, stolen from Kohana 3
// Port of Kohana3's Text::limit_chars helper
String.implement({
limitChars: function(limit, options){
var opts = {
endChar: null,
preserveWords: false
};
$extend(opts, options);
var endChar = (opts.endChar == null) ? '…' : opts.endChar;
if (this.trim() === '' || this.length <= limit) return this;
if (limit <= 0) return endChar;
if (!opts.preserveWords) return this.substr(0, limit) + endChar;
var pattern = new RegExp('^.{' + (limit-1) + '}\\S*');
var matches = this.match(pattern);
return matches[0].trim() + ((matches[0].length == this.length) ? '' : endChar);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment