wonko.com

The eclectic musings of a bitter software engineer.

How not to write a JavaScript trim function

Monday March 05, 2007 @ 11:11 AM (PST)

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?

Comments

Well if you weren't familiar with JavaScript I don't think it's too big of a leap to assume that it doesn't have regular expressions considering it doesn't even have a trim() function. But if that were the case I would also hope you wouldn't write a JavaScript application starter kit.

Monday March 05, 2007 @ 04:11 PM (PST) Posted by brunslo

AppFuse is actually a Java web app starter kit, although it includes a fair bit of JavaScript. And I'd argue that if you don't know that JavaScript has regular expression support, you probably shouldn't be writing JavaScript code intended for public consumption.

Monday March 05, 2007 @ 04:26 PM (PST) Posted by Ryan Grove
That's pretty bad, but sadly not uncommon. I'd say it's safe to assume that most folks writing javascript don't even know that it's a prototype based language or even what a js prototype is. So not terribly surprising that their technology/fluency level doesn't include regex. Still, it's a shame to see library authors this out of touch.

Personally, I've always used
replace(/^\s+|\s+$/g,''), as it doesn't rely on captures and it removes leading and trailing newlines just fine. Perhaps the g flag makes the execution slower than Crockford's?
Monday March 05, 2007 @ 09:30 PM (PST) Posted by Luke

According to Firebug's profiler and a very simple benchmark in which I made 30,000 calls to each trim method (yours, Crockford's, and AppFuse's), both your method and Crockford's averaged 0.012ms per call, whereas the AppFuse method averaged 0.034ms per call (and is broken as well, since it only trims the space character).

Monday March 05, 2007 @ 10:04 PM (PST) Posted by Ryan Grove

I didn't write the trim() function in AppFuse's global.js, but I do like yours much better. It's fixed now in Subversion. Most of the functions in global.js were added way back in 2003, so they're likely outdated and could be simplified.

Thursday March 22, 2007 @ 11:01 PM (PDT) Posted by Matt Raible

Thank you all very much for this.

Thursday October 11, 2007 @ 02:24 PM (PDT) Posted by Adriano

how to implement trim concept in this java script.

function sam() { if(!Emptycheck(document.getElementById('ddlProduct'),'','please select Product Name')){return false} else if(!Emptycheck(document.getElementById('ddlerrorcata'),'','please select the Error Category')){return false} else if(!Emptycheck(document.getElementById('txxerrorcode'),"",'please Type Error code')){return false} else if(!Emptycheck(document.getElementById('txtErrordec'),"",'please Type the Error Description')){return false} else if(!Emptycheck(document.getElementById('txtcomment'),"",'please Type Your Comment')){return false} else if(!Emptycheck(document.getElementById('txtresolution'),"",'please Type Your Resoultion')){return false} else if(!Emptycheck(document.getElementById('ddlstatus'),'','please select Status')){return false} else { return true } } function Emptycheck(obj,val,alrtmsg) { if(obj.value==val) { alert(alrtmsg); obj.focus(); return false; } else { return true; } }

Tuesday October 16, 2007 @ 11:31 AM (PDT) Posted by Rajasekaran

function trim(stringToTrim) { return stringToTrim.replace(/^\s+|\s+$/g,""); }

This seems to be a quicker solution to me....

Monday December 31, 2007 @ 11:55 AM (PST) Posted by Jason

A while ago I posted a comparison of JavaScript trim methods: see here. There's no question Crockford is a master JavaScript programmer, but his trim method you posted above is actually a pretty terrible implementation, performance wise (see my post for test results).

Monday January 07, 2008 @ 01:11 AM (PST) Posted by Steve

There definitely is different ways of doing this. Have a look at this javascript trim article.

Tuesday May 13, 2008 @ 01:37 AM (PDT) Posted by Ryan
Post a comment

Basic XHTML (including links) is allowed, just don't try anything fishy. Your comment will be auto-formatted unless you use your own <p> tags for formatting. You're also welcome to use Textile or Markdown.

Don't type anything here unless you're an evil robot:


And especially don't type anything here:

Copyright © 2002-2008 Ryan Grove. All rights reserved.
Powered by Thoth.