Home >Web Front-end >JS Tutorial >Customized and improved version of trim() for cropping string_basic knowledge

Customized and improved version of trim() for cropping string_basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:37:401079browse

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:

Copy code The code is 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 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.

Copy code The code is as follows:

function trim(text) {

return text.replace(/^s /, '').replace(/s $/, '');

}

Another improved version. Keep regular expressions as simple as possible.

Copy code The code is as follows:

function trim(text) {

//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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn