2009
07.30

Before following this article, I suggest that you read Steven Levithan’s blog on this topic.

The most recent Firefox 3.5 release supports JavaScript 1.8.1. The language came with the trim, trimLeft, trimRight methods for string. Here’s how to use it.

if (String.prototype.trim)
  ' a '.trim();

The older faster and reliable way of doing it is simply do a string replace on both the left and right.

' a '.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '');

Here’s a sample code to benchmark how they fare against each other.

start = new Date().getTime();
for(var i =0; i < 200000; i++)
	' a '.trim();
end = new Date().getTime() - start;
 
document.write('trim method uses ' + end + ' ms<br />');
 
start = new Date().getTime();
for(var i =0; i < 200000; i++)
	' a '.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '');
end = new Date().getTime() - start;
 
document.write('replace method uses ' +end + ' ms<br />');
 
start = new Date().getTime();
for(var i =0; i < 200000; i++)
	' a '.trimLeft().trimRight();
end = new Date().getTime() - start;
 
document.write('trimLeft then trimRight method uses ' + end + ' ms<br />');

Running the benchmark resulted in:
.trim() 16ms
.replace() 303ms
.trimLeft().trimRight() 30ms

That’s a superb 20x improvement in this case, and I highly recommend its usage. The code below will take care of browsers that do not support trim.

var trim = function(str) {
  return str.trim ? str.trim() : str.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '');
}

3 comments so far

Add Your Comment
  1. Hi. Interesting article. Here’s my take on even faster implementations of String.prototype.trim() in JavaScript.

    http://yesudeep.wordpress.com/2009/07/31/even-faster-string-prototype-trim-implementation-in-javascript/

    Cheers,
    Yesudeep.

  2. @Yesudeep those trimming functions are blazing fast, thanks for sharing. I will post a benchmark of those function vs native trim in the near future.

  3. My results comparing to trim19 function from http://yesudeep.wordpress.com/2009/07/31/even-faster-string-prototype-trim-implementation-in-javascript/

    trim method uses 49 ms
    replace method uses 245 ms
    trimLeft then trimRight method uses 78 ms
    trim19 method uses 188 ms

    Native trim() is extremely fast.
    i5. 4GB.Win 7. Chrome.