Fuery Solutions

14 May, 2009

Why doesn’t Mootools have a String.truncate() method?

Posted by: michael In: Uncategorized

I need a quick way to truncate strings!  I’m surprised that neither MooTools’ String.js or String.Extras.js has such a method.  They have so many super-awesome functions, methods and extensions (I especially love the Date.js extensions!!).  Yeah, I really love mootools, and I feel compelled to share with the community.  So anyway, I wrote out a simple, straightforward String.truncate() function:

Comments, suggestions, corrections and extensions are always welcomed!

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.
     * @param trail = (string) what you want appended to the end of the returned string
     *
     * @author Michael Fuery, Fuery Solutions, Inc. http://www.fuerysolutions.com/
     *
     * +Requires MooTools Core 1.2.2
     */
    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;
            s = s.slice(0,max);
            if(atChar){
                if((i = s.lastIndexOf(atChar)) != -1){
                    s = s.substring(0, i);
                }else{
                    s = s.substring(0, max);
                }
            }
 
            s += trail;
        }
 
        return s;
    }
});

No Responses to "Why doesn’t Mootools have a String.truncate() method?"

Comment Form

Our Clients Say...

The fear with any provider of technology services is that they'll cause harm, be untrustworthy, or frankly not solve the problem and waste my valuable time. Johnny Fuery and his team at Fuery Solutions have been providing me with peace of mind for a decade. I am literally baffled when colleagues complain about computer problems, because in my experience, things just work.

Patricia A. Pomper
Law Offices of Pomper & Dettenheim