JS 12 ways to remove space

Source: Internet
Author: User

Note: This article is reproduced in CSDN: Huang Hui Blogger's article " JS 12 ways to remove space "

Implementation 1

  1String. prototype function () {  2   returnthis. replace (/^\s\s*/, "). Replace (/\s\s*$/,");   3 }

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

  1String. prototype function () {  2   returnthis. replace (/^\s+/, "). Replace (/\s+$/,");   3 }

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

  1String. prototype function () {  2return this.     substring (Math. Max). Search (/\s/), 0),this. Search (/\s\s*$/) + 1);   3 }

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

  1String. prototype function () {  2   returnthis  . Replace (/^\s+|\s+$/g, ');   3 }

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 seems elegant, many class libraries use it, such as jquery and MooTools

Implementation 5

  1String. prototype function () {  2   varthis;   3   str = str.match (/\s+ (?: \ s+\s+) */);   4   return str? Str[0]: ";   5 }

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

  1String. prototype function () {  2   returnthis. Replace (/^\s* (\s* (\s+\s+) *) \s*$/, ' $ ');   3 }

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

  1String. prototype function {  2   returnthis. replace (\s* (?: \/^\s* s+\s+) *) \s*$/, ' $ ');   3 }

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

Implementation 8

  1String. prototype function () {  2   returnthis. replace (/^\s* (?: [\s\s]*\s)?) \s*$/, ' $ ');   3 }

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

  1String. prototype function () {  2   returnthis. replace (/^\s* ([\s\s]*?) \s*$/, ' $ ');   3 }

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

Implementation 10

1 String.prototype. Trim =function() {2   varstr = This,3whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\ u2029\u3000 ';4    for(vari = 0,len = str.length; i < Len; i++) {5     if(Whitespace.indexof (Str.charat (i)) = = =-1) {6str = str.substring (i);7        Break;8}9}Ten    for(i = str.)length-1; I >= 0; i--) { One     if(Whitespace.indexof (Str.charat (i)) = = =-1) { Astr = str.substring (0, i + 1); -        Break; -} the} -   returnWhitespace.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

1 String.prototype. Trim =function() {2   varstr = This,3str = str.replace (/^\s+/, ");4    for(vari = str.length-1; I >= 0; i--) {5     if(/\s/.test (Str.charat (i))) {6str = str.substring (0, i + 1);7        Break;8}9}Ten   returnStr One}

The

Implementation 10 has told us that the normal native string interception method is far better than regular substitution, 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

  1String. prototype function () {  2   varThis,  3   str = str.replace (/^\s\s*/, '),   4   WS =/\s/,  5   i = str.length;   6    while (Ws.test (Str.charat (i)));   7   return str.slice (0, i + 1);   8 }

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.

JS 12 ways to remove space

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.