This is an interview question from lgzx, which requires adding a method to JS String to remove whitespace characters (including spaces, tabs, page breaks, etc.) on both sides of the string.
= function() {
//return (/[(^\s+)(\s+$)]/g,"");//It will also remove the white space in the string
//return (/^\s+|\s+$/g,""); //
return (/^\s+/g,"").replace(/\s+$/g,"");
}
JQuery1.4.2, Mootools use
function trim1(str){
return (/^(\s|\xA0)+|(\s|\xA0)+$/g, '');
}
jQuery1.4.3, used by Prototype, this method removes g to slightly improve performance. Better performance when processing strings on a small scale
function trim2(str){
return (/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
}
After performing performance testing, Steven Levithan proposed the fastest execution of string cropping method in JS, which has better performance when processing long strings.
function trim3(str){
str = (/^(\s|\u00A0)+/,'');
for(var i=-1; i>=0; i--){
if(/\S/.test((i))){
str = (0, i+1);
break;
}
}
return str;
}
Finally, it should be mentioned that the native trim method (15.5.4.20) is added to String in ECMA-262(V5). In addition, the trimLeft and trimRight methods are added to String in the Molliza Gecko 1.9.1 engine.
Copy the codeThe code is as follows:
= function() {
//return (/[(^\s+)(\s+$)]/g,"");//It will also remove the white space in the string
//return (/^\s+|\s+$/g,""); //
return (/^\s+/g,"").replace(/\s+$/g,"");
}
JQuery1.4.2, Mootools use
Copy the codeThe code is as follows:
function trim1(str){
return (/^(\s|\xA0)+|(\s|\xA0)+$/g, '');
}
jQuery1.4.3, used by Prototype, this method removes g to slightly improve performance. Better performance when processing strings on a small scale
Copy the codeThe code is as follows:
function trim2(str){
return (/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
}
After performing performance testing, Steven Levithan proposed the fastest execution of string cropping method in JS, which has better performance when processing long strings.
Copy the codeThe code is as follows:
function trim3(str){
str = (/^(\s|\u00A0)+/,'');
for(var i=-1; i>=0; i--){
if(/\S/.test((i))){
str = (0, i+1);
break;
}
}
return str;
}
Finally, it should be mentioned that the native trim method (15.5.4.20) is added to String in ECMA-262(V5). In addition, the trimLeft and trimRight methods are added to String in the Molliza Gecko 1.9.1 engine.