JS Trim to space best practice _javascript Tips

Source: Internet
Author: User
It was just last time a classmate asked questions. Just a self-test. Let's take a look at the P33 written in "JavaScript pristine". He extended a trim () method on a String object:
Copy Code code as follows:

Function.prototype.method = function (name, func) {
This.prototype[name] = func;
return this;
};

String.method (' Trim ', function () {
Return This.replace (/^\s+|\s+$/g, "");
});

Familiar,/^\s+|\s+$/g, such regular expressions. How many frames are used. Like JQuery's Trimleft, TrimRight:
Copy Code code as follows:

Used for trimming whitespace
Trimleft =/^\s+/,
TrimRight =/\s+$/,

Is this the best practice? But our framework does not use this method (hereinafter referred to as the semi-regular method). Last time in the other product group in the internal PK, said, why our framework to use the following method to achieve the trim (), rather than the kind above.
Copy Code code as follows:

Trim:function () {
var str = this.str.replace (/^\s+/, "");
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 reason the coworker has already said, because the regular reverse matching is relatively slow . I made a comparison of its performance. In terms of overall speed and writing, the individual still favours the first one. Because the speed difference is very little. The second type is more obscure and has a lot of bytes in the code, and for a site with a high flow but with little trim (), the first one is obviously more appropriate, looking at the following test results (self test, bash here):

Ah? It's not half the way the fastest? Yes, in fact many advanced browsers already provide trim () by default. Speed is needless to say, 100 times times? Ha ha. Finally, the programme is as follows:

Copy Code code as follows:

if (! String.prototype.trim) {
String.prototype.trim = function () {
Return This.replace (/^\s+|\s+$/g, "");
}
}

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.