JavaScript method set for removing spaces _ javascript skills

Source: Internet
Author: User
A set of methods for removing spaces in JavaScript. The script home has previously released a lot of code for removing spaces, which is more comprehensive. Implementation 1

The Code is as follows:


String. prototype. trim = function (){
Return this. replace (/^ \ s */, ''). replace (/\ s * $ /,'');
}


It looks pretty bad. I used two regular expressions to replace it. The actual speed is amazing, mainly thanks to the internal optimization of the browser. A famous example of String concatenation is faster than the StringBuffer made of Array. The base2 class library uses this implementation.
Implementation 2

The Code is as follows:


String. prototype. trim = function (){
Return this. replace (/^ \ s +/, ''). replace (/\ s + $ /,'');
}


It is similar to implementation 1, but a little slower, mainly because it first assumes that at least one blank character exists. Prototype. js uses this implementation, but its name is strip, because Prototype methods all strive to be the same name as Ruby.
Implementation 3

The Code is as follows:


String. prototype. trim = function (){
Return this. substring (Math. max (this. search (/\ S/), 0), this. search (/\ S \ s * $/) + 1 );
}


The blank part is obtained as an intercept (of course, a blank character is allowed in the middle). A total of four native methods are called. The design is very clever. substring uses two numbers as parameters. Math. max takes two numbers as parameters, and search returns a number. The speed is a little slower than the two above, but faster than most below.
Implementation 4

The Code is as follows:


String. prototype. trim = function (){
Return this. replace (/^ \ s + | \ s + $/g ,'');
}


This can be called a simplified version of 2, which is to use the candidate operator to connect two regular expressions. However, in doing so, the chance of browser optimization is lost, which is inferior to 3. Because it seems elegant, many class libraries use it, such as JQuery and mootools.
Implementation 5

The Code is as follows:


String. prototype. trim = function (){
Var str = this;
Str = str. match (/\ S + (? : \ S + \ S + )*/);
Return str? Str [0]: '';
}


Match is an array, so the elements of the original string that meet the requirements become its element. To prevent the blank characters in the string from being excluded, we need to use non-capturing grouping (? : Exp ). Since the array may be empty, we will further judge it later. It seems that the browser is weak in processing the group and the word is slow. So do not be superstitious about regular expressions, although it is basically omnipotent.
Implementation 6

The Code is as follows:


String. prototype. trim = function (){
Return this. replace (/^ \ s * (\ S * (\ s + \ S +) *) \ s * $/, '$1 ');
}


Provide the required parts and put them in an empty string. However, the efficiency is poor, especially in IE6.
Implementation 7

The Code is as follows:


String. prototype. trim = function (){
Return this. replace (/^ \ s * (\ S *(? : \ S + \ S +) *) \ s * $/, '$1 ');
}


Similar to implementation 6, but non-capturing groups are used to improve the performance.
Implementation 8

The Code is as follows:


String. prototype. trim = function (){
Return this. replace (/^ \ s *((? : [\ S \ s] * \ S )?) \ S * $/, '$1 ');
}


We improved the above two ideas and used non-capturing grouping and Character Set combination? Replaced by *, the effect is amazing. Especially in IE6, we can use crazy words to describe the performance improvement and kill Firefox in seconds.
Implementation 9

The Code is as follows:


String. prototype. trim = function (){
Return this. replace (/^ \ s * ([\ S \ s] *?) \ S * $/, '$1 ');
}


This time, we replaced the non-capturing group with lazy match, which was improved in Firefox. IE was not as crazy as it was last time.
Implementation 10

The Code is as follows:


String. prototype. trim = function (){
Var str = this,
Whitespace = '\ n \ r \ t \ f \ x0b \ xa0 \ u2000 \ u2001 \ u2002 \ u2003 \ u2004 \ u2005 \ u2006 \ u2007 \ u2008 \ u2009 \ u200a \ u200b \ u2028 \ u2029 \ u3000 ';
For (var I = 0, len = str. length; I <len; I ++ ){
If (whitespace. indexOf (str. charAt (I) ===-1 ){
Str = str. substring (I );
Break;
}
}
For (I = str. length-1; I> = 0; I --){
If (whitespace. indexOf (str. charAt (I) ===-1 ){
Str = str. substring (0, I + 1 );
Break;
}
}
Return whitespace. indexOf (str. charAt (0) ===-1? Str :'';
}


I just want to say that the person who came up with this is not described by the ox, but is already of the same level as God. It first lists all possible blank characters, removes the leading space in the first traversal, and removes the trailing space in the second traversal. In the whole process, only the native method indexOf and substring are used to process strings, but no regular expressions are used. The speed is amazing. It is estimated that the internal binary implementation is directly pushed, and both IE and Firefox (other browsers certainly have no doubt) have a good performance. The speed is zero milliseconds.
Implementation 11

The Code is as follows:


String. prototype. trim = function (){
Var str = this,
Str = 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;
}


Implementation 10 tells us that the common native string truncation method is far better than regular expression replacement, although it is a little more complicated. However, as long as the regular expression is not complex, we can use the browser to optimize the regular expression to improve the program execution efficiency, such as 8 in IE performance. I don't think anyone will apply 10 in the project, because the whitespace implementation is too long and hard to remember (of course, if you are creating a class library, it is definitely the first one ). 11 is the ultimate version. The blank content in the previous section is cut down by regular expression replacement, and the Native method is used later. The effect is not inferior to that in the original version, but the speed is very backward.
Implementation 12

The Code is as follows:


String. prototype. trim = function (){
Var str = this,
Str = str. replace (/^ \ s */,''),
Ws =/\ s /,
I = str. length;
While (ws. test (str. charAt (-- I )));
Return str. slice (0, I + 1 );
}


Implementation 10 and implementation 11 are better written in simplified versions. Note that it is not about performance speed, but easy to remember and use. And its two predecessors are both zero-millisecond-level, and they will be used to work and be scary in the future.
The following is a comparison result provided by foreigners. The execution background is to trim the article Magna Carta (more than 27,600 characters.
Implement Firefox 2 IE 6
Trim1 15 ms <0.5 ms
Trim2 31 ms <0.5 ms
Trim3 46 ms 31 ms
Trim4 47 ms 46 ms
Trim5 156 ms 1656 ms
Trim6 172 ms 2406 ms
Trim7 172 ms 1640 ms
Trim8 281 ms <0.5 ms
Trim9, 125 ms, 78 ms
Trim10 <0.5 ms <0.5 ms
Trim11 <0.5 ms <0.5 ms
Trim12 <0.5 ms <0.5 ms

The Code is as follows:


// String. prototype
// Batch replace, such as str. replaceAll ([/a/g,/B/g,/c/g], ["aaa", "bbb", "ccc"])
String. prototype. ReplaceAll = function (A, B ){
Var C = this;
For (var I = 0; iC = C. replace (A [I], B [I]);
};
Return C;
};
// Remove the white spaces at both ends of the character
String. prototype. Trim = function (){
Return this. replace (/(^ [\ t \ n \ r] *) | ([\ t \ n \ r] * $)/g ,'');
};
// Remove the white space on the left of the character
String. prototype. LTrim = function (){
Return this. replace (/^ [\ t \ n \ r]/g ,'');
};
// Remove the white space on the right of the character
String. prototype. RTrim = function (){
Return this. replace (/[\ t \ n \ r] * $/g ,'');
};
// Returns the length of two characters in a Chinese character.
String. prototype. ChineseLength = function ()
{
Return this. replace (/[^ \ x00-\ xff]/g, "**"). length;
};
// Determine whether the string ends with the specified string
String. prototype. EndsWith = function (A, B ){
Var C = this. length;
Var D = A. length;
If (D> C) return false;
If (B ){
Var E = new RegExp (A + '$', 'I ');
Return E. test (this );
} Else return (D = 0 | this. substr (C-D, D) = );
};
// Determine whether the string starts with the specified string
String. prototype. StartsWith = function (str)
{
Return this. substr (0, str. length) = str;
};
// Where does the string start?
String. prototype. Remove = function (A, B ){
Var s = '';
If (A> 0) s = this. substring (0, );
If (A + B Return s;
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.