Home > Web Front-end > JS Tutorial > body text

Best practice for JS trim to remove spaces_javascript skills

WBOY
Release: 2016-05-16 18:00:04
Original
1121 people have browsed it

Just last time a classmate raised a question. Just in time to test myself. Let's first take a look at what Laodao wrote on P33 of "JavaScript Essence". He extended a trim() method to the String object:

Copy code 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, '');
});

Get familiar with it, /^s |s $/ g, such a regular expression. How many frameworks are in use? For example, jQuery's trimLeft, trimRight:
Copy code The code is as follows:

// Used for trimming whitespace
trimLeft = /^s /,
trimRight = /s $/,

Is this best practice? But our framework does not use this method (tentatively called the semi-regular method). Last time when other product groups were doing internal PK, I said why our framework should use the following method to implement trim() instead of the above one.
Copy code 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;
}

The reason has already been mentioned by the co-workers, because regular reverse matching is slower. I compared its performance. In terms of speed and writing style, I personally prefer the first writing method. Because the speed is actually very different. From the code point of view, the second type is more obscure and has a lot of bytes. For a website with high traffic but little need to use trim(), the first type is obviously more suitable. Take a look at the test results below (self-tested) , Smash here):

trim

Huh? It turns out that the semi-regular method is not the fastest? Yes, in fact, many advanced browsers already provide trim() by default. Needless to say, the speed is 100 times? Hahaha. Finally, the solution is as follows:

Copy the code The code is as follows:

if(!String.prototype. trim){
String.prototype.trim = function(){
return this.replace(/^s |s $/g, '');
}
}
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!