How not to write a JavaScript trim function

God only knows why JavaScript's String object doesn't have a trim() method to remove leading and trailing whitespace. Pretty much every other scripting language has something analogous to trim(), but JavaScript must have called in sick the day they were passing those out. This means that one of the first tasks for anyone doing any type of string processing (especially form validation) in JavaScript is to write a trim() method (or use a framework that provides one).

AppFuse describes itself as "an open source project and application that uses open source tools built on the Java platform to help you develop Web applications quickly and efficiently." In other words, AppFuse is a Java web application starter kit that provides the first fifteen layers of unnecessary complexity for you so you can concentrate on more important things, like fooling yourself into thinking Java is a good language in which to write web applications.

As my coworker Brett discovered today, the JavaScript trim() method provided by AppFuse is utterly retarded:

// This function is for stripping leading and trailing spaces
function trim(str) { 
    if (str != null) {
        var i; 
        for (i=0; i<str.length; i++) {
            if (str.charAt(i)!=" ") {
                str=str.substring(i,str.length); 
                break;
            } 
        } 
    
        for (i=str.length-1; i>=0; i--) {
            if (str.charAt(i)!=" ") {
                str=str.substring(0,i+1); 
                break;
            } 
        } 
        
        if (str.charAt(0)==" ") {
            return ""; 
        } else {
            return str; 
        }
    }
}

For comparison, here's a much more sensible JavaScript trim() implementation written by Douglas Crockford and freely available on his website:

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

However, even if we ignore the fact that AppFuse's 23-line implementation can be replaced by a one-line regular expression, there are several other things wrong with the AppFuse function. It was obviously written by a Java developer who didn't know regular expressions and wasn't at home in JavaScript. How many problems can you find?