The specific implementation code of the trim function in jquery

Source: Internet
Author: User

Because of the previous version of JavaScript 1.8.1, there is no built-in trim function, so JQuery has its own implementation. In different versions of jquery, the TRIM function is implemented differently.

Read this article to master the use of regular expressions , if not very understanding, suggest reading this. Given the powerful use of regular expressions (which are used in various languages such as Js,python,ruby,java), it is recommended to focus on learning and mastering them.

JQuery 1.7.2 version

//Intercept part of the source code, not the complete statement, is intended to illustrate the implementation process Trimleft =/^\s+/=/\s+$/""). Replace (TrimRight, "");

After simplification is

Yourstr.replace (/^\s+/, ""). Replace (/\s+$/, "")

JQuery 2.1.1 version

// the extracted part of the code, not the complete statement, is intended to illustrate the implementation process
Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latterWhiteSpa CE = "[\\x20\\t\\r\\n\\f]",
New RegExp ("^" + whitespace + "+| ( (?:^| [^\\\\]) (?:\ \\\.) *) "+ whitespace +" +$ "," G "" "";

Of course, we also have to look at other implementations:

Implementation 1

String.prototype.trim=function () {returnthis.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 () {returnthis.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 () {returnthis.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 () {returnthis.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 seems 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 () {Returnthis.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 () {Returnthis.replace (/^\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 () {Returnthis.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 () {Returnthis.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.substring (i); break;}} for (i = str.length-1; I >=0; i--) {if (Whitespace.indexof (Str.charat (i)) ===-1) {str = str.substring (0, i + 1); }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 = str.length; Whil (Ws.test (St R.charat (i))); 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.

Reference: http://www.cnblogs.com/rubylouvre/archive/2009/09/18/1568794.html

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.