Faster Javascript Trim

Want the best way to trim a sting in javascript?

A while ago, I came across a post on such a subject. It was written a few years ago but it’s still as relevant and useful as ever.

http://blog.stevenlevithan.com/archives/faster-trim-javascript 

The author basically compares a bunch of different methods to trim a string across the 2 big browsers at the time, Internet Explorer and Firefox, and figures out the fastest way of doing it.

For more detail, follow the link above, otherwise, here is the conclusion.

Fastest trim method for normal length strings

return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

Fastest trim method for super long strings

function trim11 (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

Note: For the super geeks out there, this site will show you and allow you to test what is the fastest trim method on a particular browser… enjoy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s