Javascript deletes form spaces and consecutive spaces.

Source: Internet
Author: User

Deleting spaces using the regular expression s + in js almost solves this problem. I would like to share with you the examples used in this project. I hope this will be helpful to you.

The following two requirements are required in the reply box today:

1. The text content cannot contain all spaces. Use this regular expression/^ s * $/
2. Delete consecutive spaces. This is the regular/s +/g.

The following is a common requirement code.

The Code is as follows: Copy code

<Script type = "text/javascript">
Function is_blank (str ){
Var reg =/^ s * $ /;
Return reg. test (str );
}
Function del_blank (str ){
Var reg =/s +/g;
Return str. replace (reg ,"");
}
Var str_1 = "";
Var str_2 = "aa dd gg da ";
Alert (is_blank (str_1 ));
Alert (del_blank (str_2 ));
</Script>

Currently, there are 12 methods to remove spaces in JS:

Implementation 1

The Code is as follows: Copy code
String. prototype. trim = function (){
Return this. replace (/^ ss */, ''). replace (/ss * $ /,'');
}

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: Copy code
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: Copy code
String. prototype. trim = function (){
Return this. substring (Math. max (this. search (/S/), 0), this. search (/Ss * $/) + 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: Copy code
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: Copy code
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 can be empty, we need to further judge 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: Copy code
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: Copy code
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: Copy code
String. prototype. trim = function (){
Return this. replace (/^ s *((? : [Ss] * 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: Copy code
String. prototype. trim = function (){
Return this. replace (/^ s * ([Ss] *?) 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: Copy code
String. prototype. trim = function (){
Var str = this,
Whitespace = 'hangzhou ';
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: Copy code
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: Copy code

String. prototype. trim = function (){
Var str = this,
Str = str. replace (/^ ss */,''),
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.

Related Article

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.