Home >Web Front-end >JS Tutorial >Detailed analysis of the implementation of various trims in Javascript_javascript skills

Detailed analysis of the implementation of various trims in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:071036browse

This is an interview question from lgzx company. It requires adding a method to the String of js to remove the whitespace characters (including spaces, tabs, form feeds, etc.) on both sides of the string.

Copy code The code is as follows:

String.prototype.trim = function() {
//return this.replace(/[(^s )(s $)]/g,"");//The whitespace characters in the middle of the string will also be removed
//return this.replace(/^ s |s $/g,""); //
return this.replace(/^s /g,"").replace(/s $/g,"");
}

JQuery1.4.2, Mootools uses
Copy code The code is as follows:

function trim1(str){
return str.replace(/^(s|xA0) |(s|xA0) $/g, '');
}

jQuery1. 4.3, used by Prototype, this method removes g to slightly improve performance and has better performance when processing strings on a small scale
Copy code The code is as follows:

function trim2(str){
return str.replace(/^(s|u00A0) /,'').replace(/(s|u00A0) $/, '');
}

After conducting performance tests, Steven Levithan proposed the fastest way to cut strings in JS, which has better performance when processing long strings
Copy code The code is as follows:

function trim3(str){
str = str.replace (/^(s|u00A0) /,'');
for(var i=str.length-1; i>=0; i--){
if(/S/.test(str .charAt(i))){
           str = str.substring(0, i 1); 🎜>
The last thing that needs to be mentioned is that ECMA-262 (V5) adds a native trim method (15.5.4.20) to String. In addition, the trimLeft and trimRight methods have been added to String in the Molliza Gecko 1.9.1 engine.
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