JavaScript removes form spaces and contiguous space codes

Source: Internet
Author: User

2 Requirements for today's reply box entry limit:

1, text content can not be all spaces, with this regular/^s*$/
2, delete consecutive spaces, is this regular/s+/g

The following are common requirements codes

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>

JS to remove the space method there are currently 12 kinds:

Achieve 1

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

It does not look very good, using two of regular replacements, the actual speed is very amazing, mainly thanks to the internal optimization of the browser. A well-known example string concatenation, the direct addition is faster than the stringbuffer made of array. The Base2 class library uses this implementation.
Achieve 2

The code is as follows Copy Code
String.prototype.trim = function () {
Return This.replace (/^s+/, '). Replace (/s+$/, ");
}

Similar to implementation 1, but slightly slower, mainly because it was first assumed that there was at least one blank character. Prototype.js uses this implementation, but its name is strip, because the Prototype method seeks to have the same name as Ruby.
Achieve 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);
}

A total of four native methods were called by intercepting the empty part (which, of course, allows for whitespace in the middle). The design is very ingenious, substring two numbers as a parameter. Math.max takes two digits as a parameter and search returns a number. Slower than the top two, but faster than most of the following.
Achieve 4

The code is as follows Copy Code
String.prototype.trim = function () {
Return This.replace (/^s+|s+$/g, "");
}

This can be called the implementation of the 2 simplified version, is the use of candidate operators to connect two regular. But doing so loses the chance to optimize the browser, compared to the implementation of 3. Because it appears to be elegant, many class libraries use it, such as jquery and MooTools

Achieve 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 the return of an array, so the original string conforms to the required part of its element. To prevent whitespace in the middle of the string from being excluded, we need to draw on the non-capture grouping (?: EXP). Since the array may be empty, we have to make further decisions later. As if the browser in the processing group is more powerless, a word slow. So don't be superstitious, though it's basically omnipotent.

Achieve 6

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

Provide the part that meets the requirements and place it in an empty string. But the efficiency is very poor, especially in the IE6.
Achieve 7

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

is similar to implementation 6, but it has the advantage of non capture grouping, with a little improvement in performance.

Achieve 8

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

Along the above two ideas for improvement, the use of non-capture grouping and character sets, with the replacement of *, the effect is very amazing. Especially in the IE6, you can use crazy to describe the performance of the promotion, direct seconds to kill Firefox.

Achieve 9

The code is as follows Copy Code
String.prototype.trim = function () {
Return This.replace (/^s*) ([ss]*?) s*$/, ' $ ');
}

This is a lazy match to replace the capture group, in Firefox improved, ie not the last time so crazy.

Achieve 10

The code is as follows Copy Code
string.prototype.trim = function () {
  var str = this,
  whitespace = ' Nrtfx0bxa0u2000u2001u2002u2003u2004u2005u2006u2007u20 08u2009u200au200bu2028u2029u3000 ';
  for (var i = 0,len = Str.length i < len; i++) {
    if (whitespace.indexof str.charat (i ) = = = 1) {
      str = str.substring (i);
      break;
& nbsp;  }
 }
  for (i = str.length-1 i >= 0; i--) {
    if (WhiteSpa Ce.indexof (Str.charat (i)) = = = 1) {
      str = str.substring (0, i + 1);
  &nb sp;   break;
   }
 }
  Return Whitespace.indexof (Str.charat (0)) = = = 1 str: ';
}

I just want to say that the person who made this is not a cow, it's the same level as God. It first lists all the possible whitespace characters, cuts the front blanks in the first traversal, and cuts back the blanks for the second time. The whole process uses only indexof and substring, a native method specially designed to handle strings, without using regular. Surprisingly fast, it is estimated that the internal binary implementation, and in IE and Firefox (other browsers, of course, there is no doubt) have a good performance. The speed is 0 millisecond level.
Implement one

  code is as follows copy code
string.prototype.tr im = 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 has told us that ordinary native string interception methods are far better than regular replacements, albeit a bit more complex. But as long as it is not too complex, we can use the browser for regular optimization, improve program execution efficiency, such as the implementation of 8 in IE performance. I don't think anyone would normally apply 10 to a project because that whitespace implementation is too long and too hard to remember (of course if you're building a class library, it's definitely the first). Implementation of the 11 can be described as its improved version, the front part of the blank by the regular replacement is responsible for cutting off, the back with the original method of treatment, the effect is not inferior to the original, but the speed is very adverse days.
Achieve 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));
Return Str.slice (0, i + 1);
}

Implementation of the 10 and implementation of the 11 in the formulation of a better version of the note that is not performance speed, but easy to remember and use. And its two predecessors are 0 millisecond levels, and later use this to work with the scary.

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.