ECMAScript5 has defined the native trim method for strings. This method may be faster than any version in this article. We recommend that you use native functions in supported browsers. The following describes the problems encountered by the custom trim () function and the improvement process. Kung fu is still refined in order to be mellow.
JavaScript does not have a native trim method to remove the leading and trailing spaces of a string. The most common custom trim () function implementation is as follows:
Copy codeThe Code is as follows: function trim (text ){
Return text. replace (/^ \ s + | \ s + $/g ,'');
}
This method uses a regular expression to match one or more spaces at the beginning and end of a string. The replace () method replaces all matched parts with a null string.
However, this implementation method has a performance problem based on regular expressions. This effect comes from two aspects: one is to specify the pipeline operators with two matching modes, on the other hand, it indicates the g tag that globally applies this mode.
Taking this into consideration, we can split the regular expression into two parts and remove the g tag to rewrite the function, slightly improving its speed.
Copy codeThe Code is as follows: function trim (text ){
Return text. replace (/^ \ s +/, ''). replace (/\ s + $ /,'');
}
Another improved version. Make sure that the regular expression is as simple as possible.
Copy codeThe Code is as follows: function trim (text ){
// Delete the blank header of the string
Text = text. replace (/^ \ s + /,'');
// Clear trailing spaces cyclically
For (var I = text. length; I --;){
If (/\ S/. test (text. charAt (I) {// \ S non-blank characters
Text = text. substring (0, I + 1 );
Break;
}
}
Return text;
}
Suggestion: the performance of 2nd trim () functions is good when processing short strings on a small scale. The 3rd trim functions are much faster in processing long strings.
ASIDE: the simple function of cropping the first and last blank characters of a string triggers consideration of the performance of regular expressions and avoids performance problems. The pursuit of perfection in technology can only go forward in practice.