JavaScript Remove whitespace method set _javascript tips

Source: Internet
Author: User
Achieve 1
Copy Code code as follows:

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

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
Copy Code code as follows:

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
Copy Code code as follows:

String.prototype.trim = function () {
return this. substring (Math.max (/\s/), 0), this. Search (/\s\s*$/) + 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
Copy Code code as follows:

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
Copy Code code as follows:

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
Copy Code code as follows:

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
Copy Code code as follows:

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
Copy Code code as follows:

String.prototype.trim = function () {
return this. Replace (/^\s* (?: [\s\s]*\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
Copy Code code as follows:

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

This is a lazy match to replace the capture group, in Firefox improved, ie not the last time so crazy.
Achieve 10
Copy Code code 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 made this is no longer a cow to describe 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.
Achieve 11
Copy Code code 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 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
Copy Code code as follows:

String.prototype.trim = function () {
var str = this,
str = str.replace (/^\s\s*/, ""),
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.
The following is the comparison of the results given by foreigners, the background is to Magna Carta this article (more than 27,600 characters) for the trim operation.
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

Copy Code code as follows:

String.prototype use
Batch substitution, for example: Str. ReplaceAll ([/a/g,/b/g,/c/g],["AAA", "BBB", "CCC"])
String.prototype.replaceall=function (a,b) {
var c=this;
for (Var i=0;i<a.length;i++) {
C=c.replace (A[i],b[i]);
};
return C;
};
Remove whitespace characters at both ends of a character
String.prototype.trim=function () {
Return This.replace (/(^[\t\n\r]*) | ( [\t\n\r]*$)/g, ');
};
Remove the white space character to the left of the character
String.prototype.ltrim=function () {
Return This.replace (/^[\t\n\r]/g, "");
};
Remove the white space character to the right of the character
String.prototype.rtrim=function () {
Return This.replace (/[\t\n\r]*$/g, "");
};
Returns the length of the character, one in Chinese 2
String.prototype.chineselength=function ()
{
Return This.replace (/[^\x00-\xff]/g, "* *"). Length;
};
Determines whether a 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) ==a);
};
Determines whether a string starts with the specified string
String.prototype.StartsWith = function (str)
{
Return this.substr (0, str.length) = = str;
};
How long does the string start from?
String.prototype.remove=function (a,b) {
var s= ';
if (a>0) s=this.substring (0,a);
if (a+b<this.length) s+=this.substring (a+b,this.length);
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.