The implementation of various trim in JavaScript detailed parsing _javascript tips

Source: Internet
Author: User
This is the LGZX company's interview question, asks the JS string to add a method, removes the white space character (including Space, tab, page break, etc.) on both sides of the string.
Copy Code code as follows:

String.prototype.trim = function () {
Return This.replace (/[(^\s+) (\s+$)]/g, "");//will remove whitespace from the string
Return This.replace (/^\s+|\s+$/g, ""); //
Return This.replace (/^\s+/g, ""). Replace (/\s+$/g, "");
}

Jquery1.4.2,mootools use
Copy Code code as follows:

function Trim1 (str) {
Return Str.replace (/^ (\s|\xa0) +| ( \S|\XA0) +$/g, "");
}

Jquery1.4.3,prototype use, this method removes G to slightly improve performance when handling strings on a small scale
Copy Code code as follows:

function trim2 (str) {
Return Str.replace (/^ (\s|\u00a0) +/, ""). Replace (/(\S|\U00A0) +$/, "");
}

Steven Levithan, after performing a performance test, proposes the fastest-performing clipping string in JS, which is better when dealing with long strings.
Copy 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 to mention is the addition of the native Trim method (15.5.4.20) to string in ECMA-262 (V5). In addition, the Trimleft, TrimRight method is added to string in the Molliza Gecko 1.9.1 engine.
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.