Created
October 8, 2009 06:40
-
-
Save cheeaun/204816 to your computer and use it in GitHub Desktop.
MooTools String.limitChars with 'preserve words' option, stolen from Kohana 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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