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, "");
}
}