Detailed parsing of various trim implementations in Javascript

  • 2020-03-30 00:45:46
  • OfStack

This is an interview question from LGZX company, which requires adding a method to js String to remove white space characters (including Spaces, tabs, page breaks, etc.) from both sides of the String.

String.prototype.trim = function() { 
    //return this.replace(/[(^s+)(s+$)]/g,"");// Remove the blank character from the inside of the string  
    //return this.replace(/^s+|s+$/g,""); // 
    return this.replace(/^s+/g,"").replace(/s+$/g,""); 
}

JQuery1.4.2, Mootools usage  

function trim1(str){ 
    return str.replace(/^(s|xA0)+|(s|xA0)+$/g, ''); 
}

JQuery1.4.3, used by Prototype, which removes g to slightly improve performance on a smaller scale when dealing with strings

function trim2(str){ 
    return str.replace(/^(s|u00A0)+/,'').replace(/(s|u00A0)+$/,''); 
}

After performance testing, Steven Levithan proposed the fastest string clipping method in JS, which has better performance when dealing with long strings

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

Last but not least, the native trim method (15.5.4.20) was added to the String in ecma-262 (V5). In addition, trimLeft and trimRight methods were added to String in the Molliza Gecko 1.9.1 engine.

Related articles: