JavaScript: Non-regex trim function

Surprisingly, JavaScript does not have a native “trim” function. Trim should remove all whitespace from the beginning and ending of a string. If you are using jQuery, you can use jQuery trim. Many other libraries include a trim function.

If you Google for JavaScript trim functions, you’ll find that they usually use regular expressions. One would think that would be good enough. However, I encountered a situation where the typical regex whitespace trim functions simply weren’t working. Perhaps it is was an unusual whitespace character?

I found a great article that compared different JavaScript trim functions. The function he listed as “trim10” does not use regular expressions at all. It is also one of the best performers in terms of efficiency/speed. Most importantly, this function successfully trimmed my pesky whitespace!

Sharing this fast, functional, non-regex JavaScript trim function in hopes it’ll be useful:

function trim (str) {
	var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
	for (var i = 0; i < str.length; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	}
	for (i = str.length - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

1 Comment on JavaScript: Non-regex trim function

Leave a Reply

Your email address will not be published. Required fields are marked *