Introduction

Following Steven Levithan's old post about string trimming.

I decided to give it another try after my first proposal.

I made a trim version, based on my aforementioned first attempt. It seems to be much faster on any browser and with different (string) lengths and whitespaces.

First of all...

I want to make clear that this version doesn't trim the exact same characters that other versions do.

In my first version, I simply tried to improve Steven's version without really giving it a deep thought.

This time I thought:Are all those characters really relevant?.

After thinking about this for a while I decided that, whatever /\s/ matches, should be trimmed.

Why ? because most major js libraries use the regex version. If their users are content, then those are the needed characters. Also, if my function would actually do better than others, it could go directly to jQuery's core (there's a ticket for that).

So I created a test page. The results weren't equal for all browsers, IE and Safari 3 yielded far less charCodes. I decided these are the ones I want to trim.

My Trim function

So, the basic modification I made to my previous version, was to check whether the charCode is lower than 33 instead of the whole map/object.

This one takes much less code and is quite faster, I humbly named it "myBestTrim", here it is:

function myBestTrim( str ){ var start = -1 , end = str. length ; while ( str. charCodeAt (--end) < 33 ); while ( str. charCodeAt (++start) < 33 ); return str. slice ( start, end + 1 ); };

The Benchmark

If you want to try the benchmark, get in here. The number should you care about (in my opinion) is the minimum. That's probably the one that ran a lower CPU level.

That test uses a string with 10K characters. Sounds like a lot but this blog's homepage has 55K of html. As oposed to a regex-based trim, this one should scale pretty well, because it doesn't need to check all the string.

That's actually why I removed any regex-based approach from this test, because they'd take too long.

If you have Firebug, I'd advice you to turn it off before getting into this test.

I made a similar test with small strings. It uses a string of 30 characters with 3 whitespaces on each side. In this case, the difference was smaller but still noticeable.

The only situation where another function was faster was on IE, with a small string WITH whitespaces. In this situation, jQuery's trim (the typical regex-based trim) was slightly faster, my trim got 2nd place.

Most situations don't really require much trimming and critical situations have very large strings, so I think this function scales well on those 2.

Conclusion

If all goes well, I'll put this function into jQuery's core. I'd like though, to get some results from other users, to verify my trim is really fast and effective.

Here's the ticket requesting a faster trim for jQuery: #2279.

11/6/08

Removed a dispensable check, thanks Andrea Giammarchi.