Wednesday, March 20, 2013

Native JavaScript Trim String Function (best performance)

Hi, All.

As we may already notice, sometimes we meet functionality requirements on page, app or extension that is quiet short and simple. There is no taste to load JavaScript Libraries such as jQuery, Prototype, ExtJS or any other. But using native JS made difficult for developers who only experienced with libraries, nowadays is a new trend.
Developer may tell you that he knows javascript, but reality proves that he only knows how to work with jquery and that is the end of his javascript knowledge.
My opinion, if coder tells you that he knows javascript - he must know it's internals.

Native javascript function TRIM to trim strings:

The trim function i'v coded is based on Steven Leviathan's researches and benchmarks of trimming methods.
Under these circumstances, i am not really developed it, but wrapped into a default String object's prototype to allow simpler use of string trimming function.
Take a look at the function, after the function is an example.
/**
 * Trim string method (regex way), based on Steven Levithan researches.
 *      Fastest triming on short strings, different aproach must be used for documents triming.
 * @author Rusevych Valentin
 * @since 16 Dec 2012
 * @return string trimmed.
 */
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () {
        return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // fastest method (~8.5ms per 1000 iterations)
    }
}

/**
 * Usage Example
 **/
var s = '  TestString ';
s.trim();
console.log(s);
// output "TestString"


Take it into your file of "usable" functionality.
Sincerely,
VR

No comments: