Native implementation of the JavaScript removal space trim ()

Source: Internet
Author: User

The people's brains were kicked by the donkey until javascript1.8.1 support the Trim function (and trimleft,trimright), but now only firefox3.5 support. Because it is too often used to remove whitespace on both sides of a string, each large class library has its shadow. In addition, foreigners are very research spirit, make a lot of drums to achieve. Guangde County Energy Bureau

Implementation 1
String.prototype.trim = function () {  return this.replace (/^\s\s*/, "). Replace (/\s\s*$/, ');}

It doesn't look very good, with two regular replacements, the actual speed is amazing, thanks to the browser's internal optimizations. A well-known example string concatenation, the direct addition than the array made of StringBuffer is also faster. This implementation is used by the Base2 class library.

Implementation 2
String.prototype.trim = function () {  return this.replace (/^\s+/, "). Replace (/\s+$/, ');}

Similar to implementation 1, but slightly slower, the main reason is that it first assumes that there is at least one whitespace character. Prototype.js uses this implementation, but its name is strip, because Prototype's approach seeks to have the same name as Ruby.

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

A total of four native methods were called by capturing a blank part (which, of course, allowed the presence of whitespace in the middle). The design is very ingenious, substring with two numbers as parameters. Math.max takes two numbers as arguments, and search returns a number. Slower than the above two, but faster than most of the following.

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

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

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

Match returns an array, so that the original string conforms to the required part and becomes its element. To prevent whitespace in the middle of the string from being excluded, we need to use a non-capturing grouping (?: EXP). Since the array may be empty, we will make further judgments later. As if the browser in the processing group on the weak, a word slow. So don't be superstitious, though it's basically omnipotent.

Implementation 6
String.prototype.trim = function () {  return This.replace (/^\s* (\s* (\s+\s+) *) \s*$/, ' $ ');}

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

Implementation 7
String.prototype.trim = function () {return This.replace (/^\s* (= \s* (?: \ s+\s+) *) \s*$/, ' $ $ ');}

Similar to implementation 6, but with the advantage of non-capturing grouping, the performance effect is a little bit improved.

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

Along the above two ideas to improve the use of non-capturing groups and character sets, with the replacement of *, the effect is very amazing. Especially in the IE6, you can use madness to describe the performance of the promotion, direct seconds to kill Firefox.

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

This is a lazy match to replace the non-capturing group, in Firefox improved, ie not last so crazy.

Implementation 10
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.subs Tring (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 made this is not an ox, it is the same level as God. It first lists the possible whitespace characters, cuts out the front blanks in the first traversal, and the second time cuts back the blanks. The whole process only uses indexof and substring, a native method specifically designed to handle strings, without using a regular. The speed is staggering, it is estimated to be in the internal binary implementation, and in IE and Firefox (other browsers of course, there is no doubt) have a good performance. The speed is at 0 millisecond levels.

Implementation 11
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 has told us that the normal native string interception method is far better than regular replacement, albeit a bit more complex. But as long as the regular is not too complicated, we can use the browser to optimize the regular, improve program execution efficiency, such as the implementation of 8 in IE performance. I don't think anyone would normally apply implementation 10 to a project, because that whitespace is too long to remember (if you're building a class library, of course, it's definitely first). Implementation 11 is its improved version, the front part of the blank by the regular replacement is responsible for cutting off, followed by the original method of processing, the effect is not inferior to the original, but the speed is very inverse day.

Implementation 12
String.prototype.trim = function () {  var str = this,  str = str.replace (/^\s\s*/, '),  ws =/\s/,  i = St R.length;  while (Ws.test (Str.charat ()));  Return Str.slice (0, i + 1);}

Implementation of 10 and implementation of 11 in a better version of the wording, note that is not performance speed, but easy to remember and use on. And its two predecessors are all 0-millisecond levels, and then use this to work and scare.

The following is the comparison results given by the foreigner, the execution background is Magna Carta this article (more than 27,600 characters) to trim operations.

Implement Firefox 2 IE 6
Trim1 15ms < 0.5ms
Trim2 31ms < 0.5ms
Trim3 46ms 31ms
Trim4 47ms 46ms
Trim5 156ms 1656ms
Trim6 172ms 2406ms
Trim7 172ms 1640ms
Trim8 281ms < 0.5ms
Trim9 125ms 78ms
Trim10 < 0.5ms < 0.5ms
Trim11 < 0.5ms < 0.5ms
Trim12 < 0.5ms < 0.5ms

Native implementation of the JavaScript removal space trim ()

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.