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.
String.prototype.trim = function() {
//return this.replace(/[(^s )(s $)]/g,"");//The whitespace characters in the middle of the string will also be removed
//return this.replace(/^ s |s $/g,""); //
return this.replace(/^s /g,"").replace(/s $/g,"");
}
JQuery1.4.2, Mootools uses
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 and has better performance when processing strings on a small scale
function trim2(str){
return str.replace(/^(s|u00A0) /,'').replace(/(s|u00A0) $/, '');
}
After conducting performance tests, Steven Levithan proposed the fastest way to cut strings in JS, which has better performance when processing 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); 🎜>
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.