This is an interview question from lgzx company. It requires adding a method to the String of js to remove the whitespace characters (including spaces, tabs, form feeds, etc.) on both sides of the string.
Copy the code code as follows:
String.prototype.trim = function() {
//return this.replace(/[(^/s+)(/s+$)]/g,"");//Remove the whitespace characters in the string
//return this.replace(/^/s+|/s+$/g,""); //
return this.replace(/^/s+/g,"").replace(//s+$/g,"");
}
JQuery1.4.2, used by Mootools
Copy the code code as follows:
function trim1(str){
return str.replace(/^(/s|/xA0)+|(/s|/xA0)+$/g, '');
}
jQuery1.4.3, used by Prototype. This method removes g to slightly improve performance. It has better performance when processing strings on a small scale.
Copy the code code as follows:
function trim2(str){
return str.replace(/^(/s|/u00A0)+/,'').replace(/(/s|/u00A0)+$/,'');
}
After conducting performance testing, Steven Levithan proposed the fastest way to trim strings in JS, which has better performance when processing long strings.
Copy the code code as follows:
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;
}
The last thing that needs to be mentioned is that ECMA-262 (V5) adds a native trim method (15.5.4.20) to String. In addition, the trimLeft and trimRight methods have been added to String in the Molliza Gecko 1.9.1 engine.