This article mainly introduces the implementation of various trim in Javascript in detail. If you need a friend, please refer to it and hope to help you. This is an interview question from lgzx, add a method to the String of js to remove the blank characters (including spaces, tabs, and page breaks) on both sides of the String ).
The Code is as follows:
String. prototype. trim = function (){
// Return this. replace (/[(^ \ s +) (\ s + $)]/g, ""); // removes the blank characters in the string.
// Return this. replace (/^ \ s + | \ s + $/g ,"");//
Return this. replace (/^ \ s +/g, ""). replace (/\ s + $/g ,"");
}
JQuery1.4.2, used by Mootools
The Code is as follows:
Function trim1 (str ){
Return str. replace (/^ (\ s | \ xA0) + | (\ s | \ xA0) + $/g ,'');
}
JQuery1.4.3 and Prototype are used. This method removes g to slightly improve the performance when processing strings on a small scale.
The Code is as follows:
Function trim2 (str ){
Return str. replace (/^ (\ s | \ u00A0) +/, ''). replace (/(\ s | \ u00A0) + $ /,'');
}
Steven Levithan proposed the fastest way to crop strings in Javascript after performing performance tests. This provides better performance when processing long strings.
The Code is 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;
}
Finally, we need to mention that the native trim method (15.5.4.20) is added to the String in the ECMA-262 (V5 ). In addition, the trimLeft and trimRight methods are added to the String in the engine Molliza Gecko 1.9.1.