ECMAScript5 has defined a native trim method for strings. This method is probably faster than any version of this article. It is recommended to use native functions in supported browsers. The following describes the problems encountered by the custom trim() function and the improvement process. Kung Fu can only be perfected through constant tempering.
There is no native trimming method in JavaScript for removing leading and trailing whitespace from a string. The most common custom trim() function implementation is as follows:
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 a string. The replace() method replaces all matching parts with an empty string.
However, this implementation has a performance problem based on regular expressions. This impact comes from two aspects: on the one hand, it specifies the pipeline operator with two matching patterns, and on the other hand, it specifies g to apply the pattern globally. mark.
With this in mind, the function can be rewritten by splitting the regular expression in two and removing the g tag, making it slightly faster.
return text.replace(/^s /, '').replace(/s $/, '');
}
Another improved version. Keep regular expressions as simple as possible.
//Delete the leading blank of the string
text = text.replace(/^s /, '');
//Loop to clear trailing blanks
for(var i=text.length; i--; ) {
if(/S/.test(text.charAt(i))) { // S non-whitespace character
text = text.substring(0, i 1);
break;
}
}
return text;
}
Usage suggestions: The performance of the second trim() function is still good when processing short strings on a small scale. The third trim function is significantly faster when processing long strings.
Off-topic: A simple function to cut the leading and trailing whitespace characters of a string has led to the consideration of performance issues of regular expressions and the implementation of methods to avoid performance issues. Technology pursues perfection and can only move forward in practice.