Js 12 utility methods for removing whitespace

  • 2020-03-26 23:47:34
  • OfStack

To achieve 1


String.prototype.trim = function() {
 return this.replace(/^ss*/, '').replace(/ss*$/, '');
}

It didn't look that good, it took two regex substitutions, and the actual speed was amazing, thanks largely to the browser's internal optimizations. A famous example of string concatenation is the direct addition of strings faster than the StringBuffer made with Array. The base2 class library USES this implementation.

The 2


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

It's similar to implementation 1, but a bit slower, mainly because it starts with the assumption that at least one blank character exists. Prototype.js USES this implementation, but it's called strip, because Prototype's methods are all aimed at having the same name as Ruby.

Implement 3


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

In total, four native methods are called by intercepting to get the white space (with white space in between, of course). Cleverly designed, the substring takes two Numbers as arguments. Math.max takes two Numbers as an argument, and search returns a number. It's a little slower than the top two, but faster than most of the bottom two.

To achieve 4


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

This is a simplified version of implementation 2, which USES candidate operators to join two regularisms. But doing so misses the opportunity for browser optimization, as opposed to implementation 3. Because it looks elegant, many libraries, such as JQuery and mootools, use it

Implement 5


String.prototype.trim = function() {
 var str = this;
 str = str.match(/S+(?:s+S+)*/);
 return str ? str[0] : '';
}

A match returns an array, so the part of the original string that meets the requirements becomes its element. To prevent the white space in the middle of the string from being excluded, we need to invoke the non-trapping grouping (? : exp). Since the array can be null, we will make further decisions later. It seems that the browser is weak on grouping, one word slow. So don't be superstitious about regularity, which is basically omnipotent.

To achieve 6


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

Provide the required part into an empty string. However, it is very inefficient, especially in IE6.

Realization of 7


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

Similar to implementation 6, but with the benefit of non-capture grouping, performance is slightly improved.

To achieve 8


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

Along with the above two ideas to improve the use of non-capture grouping and character set, with ? Replace the *, and the results are amazing. Especially in IE6, can describe this performance improvement with the use of crazy, direct seconds kill firefox.

Implement 9


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

Instead of a non-capture group, lazy matching is used this time, which is improved in firefox, IE is not as crazy as last time.

Achieve 10


String.prototype.trim = function() {
 var str = this,
 whitespace = ' nrtfx0bxa0u2000u2001u2002u2003u2004u2005u2006u2007u2008u2009u200au200bu2028u2029u3000';
 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 created this is no longer described as a cow, but as a god. It starts with a list of all possible whitespace characters, cutting off the first whitespace and the second whitespace. The whole process USES only indexOf and substring, which are native methods for dealing with strings, and does not use regularization. It is surprisingly fast, probably up to the internal binary implementation, and works well in IE and firefox (and no doubt in other browsers). The speed is zero milliseconds.

Realization of 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 shown us that the normal native string interception method is much better than regular substitution, although it is a bit more complicated. But as long as the regularization is not too complex, we can use the browser to regularization optimization, improve the execution efficiency of the program, such as 8 in IE performance. I don't think anyone usually applies implementation 10 in a project because the whitespace implementation is too long to remember (of course if you're building a library, it's definitely the first). Implementation 11 is an improved version, with the first part of the white space to be cut by the regular replacement, and the second part to be processed by the native method, the effect is not as good as the original, but the speed is very bad.

Implementation of 12


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 improvements in writing, not in terms of performance speed, but in terms of ease of use. And both of its predecessors are zero milliseconds, which will be used to work and scare people later.

JS(before and after Spaces removed or all Spaces removed) usage

1. Remove all Spaces before and after the string:

The code is as follows:


function Trim(str){ 
 return str.replace(/(^s*)|(s*$)/g, ""); 
}

Description:

If you use jQuery, just use the $.trim(STR) method, which represents a string that removes all the Spaces before and after.

2. Remove all Spaces in the string (including intermediate Spaces, the second parameter should be set as :g)

The code is as follows:


function Trim(str,is_global){
  var result;
  result = str.replace(/(^s+)|(s+$)/g,"");
  if(is_global.toLowerCase()=="g")
      {
        result = result.replace(/s/g,"");
       }
      return result;
}


Related articles: