Detailed analysis of various trim implementations in Javascript _ javascript tips-js tutorial

Source: Internet
Author: User
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.