This project is archived and is in readonly mode.

#670 ✓wontfix
Michael Fuery

New addition: String.truncate() method

Reported by Michael Fuery | May 15th, 2009 @ 05:59 PM

I constantly find a need to truncate a string and was surprised that MooTools Core did not contain such a function. So I wrote a quick little method to do that, I think it is robust and it has 3 optional parameters to customize the truncating behavior. Tell me what you think about it and, by all means, include it in the next release if you see fit! If so, I'm sure you'll rewrite it a bit to conform more strictly to mootools code style. Code snippet attached.

String.implement({

/**
 * String.truncate(max, atChar, trail)
 *
 * ++All parameters are optional.
 * @param max = (integer) maximum length of truncated string. Defaults to 100 chars.
 * @param atChar = (string) truncate at the last index of this string. If not found, just truncates to max length.
 *                 If null, does not search and truncates to max length. Defaults to split at space.
 * @param trail = (string) what you want appended to the end of the returned string. Defaults to '...'
 *
 * @author Michael Fuery, Fuery Solutions, Inc. http://www.fuerysolutions.com/
 *
 * +Requires MooTools Core
 */
truncate:function(max, atChar, trail){
    var s = this.trim();
    if(s.length<1) return '';
    if(!$defined(max)) var max = 100;
      else max = max.toInt();
    if(!$defined(atChar)) var atChar=' '; // break at space
      else if(atChar == null) var atChar=false;
    if(!$defined(trail)) var trail = '...';

    if(s.length > max) {
        var i=0;
        if(atChar){
            if((i = s.lastIndexOf(atChar)) != -1){
                s = s.substring(0, i);
            }else{
                s = s.substring(0, max);
            }
        }

        s += trail;
    }

    return s;
}

});

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Shared Ticket Bins

Attachments

Tags

Pages