ECMASCRIPT5 has defined the native Trim method for the string. This method may be faster than any version of this article. It is recommended that you use native functions in supported browsers. The following is a discussion of the problems encountered with the custom trim () function and the process of improvement. Kung Fu is constantly quenched in order to mellow.
There is no native pruning method in JavaScript for removing string-and-tail whitespace. The most common custom trim () function implementation looks like this:
Copy Code code as follows:
function Trim (text) {
Return Text.replace (/^\s+|\s+$/g, "");
}
This implementation uses a regular expression to match one or more whitespace characters at the beginning and end of the string. The replace () method replaces all matching parts with an empty string.
This implementation, however, has a performance problem based on regular expressions, which comes from two aspects: one is to indicate a pipe operator with two matching patterns, and the other is to indicate a G-tag that applies the pattern globally.
With these in mind, the regular expression can be split in Split and the G-tag removed to rewrite the function, slightly increasing its speed.
Copy Code code as follows:
function Trim (text) {
Return Text.replace (/^\s+/, '). Replace (/\s+$/, ");
}
Another version of the improvement. Ensure that regular expressions are as simple as possible.
Copy Code code as follows:
function Trim (text) {
Remove head whitespace from a string
Text = Text.replace (/^\s+/, ' ");
Loop Clear trailing blanks
for (var i=text.length; i--;) {
if (/\s/.test (Text.charat (i))) {//\s Non-white-space character
Text = text.substring (0, i+1);
Break
}
}
return text;
}
Recommendations for use: the 2nd trim () function is good when dealing with short strings on a small scale. The 3rd trim function is significantly faster when working with long strings.
Digression: Simple clipping of the character function of the end of the string, the performance of the regular expression to consider the problem and achieve the avoidance of performance problems. Technical pursuit of perfection, only in the practice of the forward.