Category: >> JavaScript >> Fastest javascript Trim() function Bookmark and Share

<< lastnext >>

Snippet Name: Fastest javascript Trim() function

Description: Many implementations of trim() in javascript are poorly written, slow, and/or inefficient. Blogger Steven Levithan did extensive testing of over a dozen trim() functions for javascript. The two versions here were the "winners" in terms of speed and handling of long strings.

Comment: Found on Steven Levithan's blog at:

Author: Steven Levithan
Highlight Mode: JAVASCRIPT
Last Modified: January 24th, 2011

// a general-purpose implementation which 
// is very fast across most browsers:
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
// this hybrid version handles long strings 
// exceptionally fast in all browsers:
function trim12 (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© | users online: 10