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:
http://blog.stevenlevithan.com/archives/faster-trim-javascript
Author: Steven Levithan
Language: JAVASCRIPT
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);
}
|