Implement a trim method
Javascript1.8.1 supports the trim method. Because it is so common to remove whitespace from the sides of strings, it can be found in all kinds of libraries. Foreigners are very research spirit, made quite a lot of implementation.
Trim1
: Used two regular substitutions, the actual speed is amazing, mainly due to the internal optimization of the browser.
A famous example of string concatenation is that adding directly is faster than StringBuffer made from Array. The Base2 class library uses this implementation.
String.prototype.trim = function() {
return this.replace(/^\s\s*/.' ').replace(/\s\s*$/.' ');
}
Copy the code
Trim2
: Similar to Trim1, but slightly slower, because it does not trigger all the same optimizations.
The main reason is that it assumes at least one whitespace character in the first place. Prototype.js uses this implementation, but it’s called Strip because Prototype’s methods aim to have the same name as Ruby.
String.prototype.trim = function() {
return this.replace(/^\s+/.' ').replace(/\s+$/.' ');
}
Copy the code
Trim3
: This is usually faster than the following methods, but slower than the above two methods. Its speed comes from using simple character index lookups.
A total of four native methods are called to intercept the whitespace (with whitespace allowed, of course). Very cleverly designed, subString takes two numbers as arguments. Math.max takes two numbers and search returns a number.
String.prototype.trim = function() {
return this.substring(Math.max(this.search(/\S/), 0),this.search(/\S\s*$/) + 1);
}
Copy the code
Trim4
This is a simplified version of the real Trim2 that uses the candidate operator to join two re’s. But that’s a missed opportunity for browser optimization, not as good as Trim3. Because it looks elegant, many class libraries use it, such as JQuery and MooTools
This often well-thought-out approach is easily the most commonly used approach in JavaScript libraries today. In general, this is the fastest implementation only if you use short strings with no leading or trailing Spaces. This advantage is partly due to the initial character discrimination optimization it triggers. Although this is a relatively good executor, it is slower than the above three methods when working with longer strings because top-level alternation prevents many optimizations that might otherwise be initiated.
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g.' ');
}
Copy the code
Trim5
: match returns an array, so the parts of the string that match become its elements. To prevent whitespace in the middle of the string from being excluded, we need to invoke non-trapping groups (? : exp). Since the array may be empty, we have to make a further determination later. It seems that the browser is weak on grouping, one word at a time. So don’t put too much faith in regex, which is basically everything.
In general, this is the fastest method when dealing with empty strings or strings containing only Spaces, because it triggers the pre-check for the required character optimizations. Note: In IE6, this can be slow when using long strings.
String.prototype.trim = function() {
var str = this;
str = str.match(/\S+(? :\s+\S+)*/);
return str ? str[0] : ' ';
}
Copy the code
Trim6
: Supply the parts that meet the requirements into an empty string. The approach is similar to (but inferior to) Trim8.
There is no good reason to use it in JavaScript, especially since it can be very slow in IE6.
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/.'$1');
}
Copy the code
Trim7
: Similar to Trim6, but faster due to the use of non-capture groups (which don’t work in IE 5.0 and below). Again, this can be slow in IE6.
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(? :\s+\S+)*)\s*$/.'$1');
}
Copy the code
Trim8
: Improved along the above two ideas, using non-capture groups and character sets, using? Replaced *, the effect is very amazing. Especially in IE6, you can use crazy to describe this performance improvement, directly killing Firefox.
The performance difference indicates that IE is well optimized for quantization of the “any character” tag.
String.prototype.trim = function() {
return this.replace(/^\s*((? :[\S\s]*\S)?) \s*$/.'$1');
}
Copy the code
Trim9
: Lazy matching replaces non-capture grouping this time, improved in Firefox, IE is not as crazy as last time.
In general, this is the fastest for very short strings that contain non-space characters and margin whitespace. The advantage is that it uses a simple, one-pass, lazy approach. Like Trim8, this is much faster in IE6 than Firefox 2.
String.prototype.trim = function() {
return this.replace(/^\s*([\S\s]*?) \s*$/.'$1');
}
Copy the code
Trim10
: First list all possible whitespace, cut the front whitespace on the first pass and the back whitespace on the second pass. It uses only indexOf and SubString, the native methods for handling strings, without using regex. It’s astonishingly fast, probably right up to the internal binary implementation, and works well in Internet Explorer and Firefox (and no doubt other browsers). The speed is zero milliseconds.
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 : ' ';
}
Copy the code
Trim11
Trim10 has shown us that normal native string interception is far better than regular substitution, although it is a bit more complicated. However, as long as the re is not too complex, we can take advantage of the browser’s re optimization to improve the performance of programs, such as Trim8 in IE. I don’t think anyone would normally use Trim10 in a project because the Whitespace implementation is too long to remember (of course, if you’re building a class library, it would definitely come first). Trim11 is an improved version of Trim11, with regular substitutions to cut whitespace in the front and native methods to deal with it. The effect is as good as the original, but the speed is very insane.
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;
}
Copy the code
Trim12
: Trim10 and Trim11 are better improved versions in writing, note that the performance is not speed, but easy to remember and use. And its two predecessors are both at the zero millisecond level, and later use this to work with scary.
String.prototype.trim = function() {
var str = this,
str = str.replace(/^\s\s*/.' '),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
Copy the code
Compare the results
Trim | Firefox 2 | IE 6 |
---|---|---|
Trim1 | 15ms | < 0.5 ms |
Trim2 | 31ms | < 0.5 ms |
Trim3 | 46ms | 31ms |
Trim4 | 47ms | 46ms |
Trim5 | 156ms | 1656ms |
Trim6 | 172ms | 2406ms |
Trim7 | 172ms | 1640ms |
Trim8 | 281ms | < 0.5 ms |
Trim9 | 125ms | 78ms |
Trim10 | < 0.5 ms | < 0.5 ms |
Trim11 | < 0.5 ms | < 0.5 ms |
Trim12 | < 0.5 ms | < 0.5 ms |
Original link:www.cnblogs.com/rubylouvre/…
Implement a deepClone method
How to write a deep copy that will impress your interviewer
Add (1) (2) (3)
Add (1), add(2), add(3), add(1), add(2), add(3)
Addition of large Numbers
Pat down practice group
Realize the anti – shake function
Implement throttling function
String inversion
Array to heavy
Implement thousands separator
It is a very common problem to convert ordinary numbers to a string of numbers in the thousand separator format, where the rule is that the integer parts of a number are grouped in three digits, separated by a comma. The decimal part is not divided into sections. Example: 19351235235 767
There are several common implementations.
- Methods a
The idea is to convert a number into an array of characters, loop through the array, add a comma for every three digits, and merge it into a string. Because delimiters are added backwards in order: for example, 1234567 was added to 1,234,567 instead of 123,456,7, it is convenient to reverse the array first, and then reverse it back to the normal order. Note that if numbers have decimals, separate the decimals.
function numFormat(num){
num=num.toString().split("."); // Separate the decimal points
var arr=num[0].split("").reverse(); // Convert to an array of characters and sort in reverse order
var res=[];
for(var i=0,len=arr.length; i<len; i++){if(i%3= = =0&&i! = =0){
res.push(","); // Add a delimiter
}
res.push(arr[i]);
}
res.reverse(); // Reverse order again to make the correct order
if(num[1]) {// Add decimals if there are decimals
res=res.join("").concat("."+num[1]);
}else{
res=res.join("");
}
return res;
}
var a=1234567894532;
var b=673439.4542;
console.log(numFormat(a)); / / "1234567894532"
console.log(numFormat(b)); / / "673439454"
Copy the code
- Method 2
Use the javascript function toLocaleString
Syntax: numObj. ToLocaleString ([locales [, options]])
The toLocaleString() method returns the locale-specific representation string for this number.
var a=1234567894532;
var b=673439.4542;
console.log(a.toLocaleString()); / / "1234567894532"
console.log(b.toLocaleString()); // "673,439.454"
Copy the code
- Methods three
Using regular expressions and the replace function, I prefer this approach to the first two, although the regex is a little hard to understand.
The replace syntax: STR. Replace (regexp | substr, newSubStr | function)
The first RegExp
The object or its literal that matches is replaced by the return value of the second argument.
Function numFormat(num){var res= num.tostring ().replace(/\d+/, function(n){return n.place (/(\d)(? =(\d{3})+$)/g,function($1){ return $1+","; }); }) return res; } var a=1234567894532; Var b = 673439.4542; console.log(numFormat(a)); / / "1234567894532" the console. The log (numFormat (b)); / / "673439454"Copy the code
Original link:www.jianshu.com/p/928c68f92…