I came back to the learning framework. Seeing the expansion of the String object, I am more interested in trim (), a method that is often mentioned, just as some people raised questions last time. You can test it on your own. Let's take a look at what I wrote in "JavaScript essence" P33. He extended a trim () method for the String object:
The Code is 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 with this regular expression, such as/^ \ s + | \ s + $/g. How many frameworks are in use. For example, trimLeft and trimRight of jQuery:
The Code is as follows:
// Used for trimming whitespace
TrimLeft =/^ \ s + /,
TrimRight =/\ s + $ /,
Is this the best practice? However, our framework does not use this method (currently called semi-regular method ). The last time I talked about the internal PK of other product groups, why does our framework use the following method to implement trim () instead of the above method.
The Code is 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;
}
This is becauseReverse matching of regular expressions is slow.. I have compared its performance. In terms of overall speed and writing, individuals prefer the first writing method. Because the speed difference is very small. The second type of code is obscure and has many bytes. This is obviously suitable for websites with high traffic but few trim () requests, take a look at the following test results (self-test, click here ):
Ah? Isn't it the fastest way to use semi-regular expressions? Yes, trim () is provided by default in many advanced browsers. Not to mention speed, 100 times? Hahaha. Finally, the solution is as follows:
The Code is as follows:
If (! String. prototype. trim ){
String. prototype. trim = function (){
Return this. replace (/^ \ s + | \ s + $/g ,'');
}
}