//跨浏览器,性能稳定
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+/,"").replace(/\s+$/, "");
}
}
// 长字符串操作时变慢
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
}
// 长字符串操作时很慢
String.prototype.trim = function() {
return this.replace(/^\s*([\s\S]*?)\s*$/,"$1");
}
// 字符串尾部空格较少时比较快
String.prototype.trim = function() {
return this.replace(/^\s*([\s\S]*\S)?\s*$/,"$1");
}
// 最慢
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1");
}
// 不受字符串长度影响,只和空白字符个数有关
String.prototype.trim = function() {
var start = 0,
end = this.length - 1,
ws = "\n\r\t\f\x0b\xa0\u1680\u180e\u2000\u2001\u2002\u2003
\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f
\u205f\u3000\ufeff";
while (ws.indexOf(this.charAt(start)) > -1) {
start++;
}
while (end > start &&ws.indexOf(this.charAt(end)) > -1) {
end--;
}
return this.slice(start, end + 1);
}
// 混合方案
String.prototype.trim = function() {
var str = this.replace(/^\s+/, ""),
end = str.length - 1,
ws = /\s/;
while (ws.test(str.charAt(end))) {
end--;
}
return str.slice(0, end + 1);
}
Summary
• When concatenating numerous or large strings, array joining is the only method with reasonable performance in IE7 and earlier.
• If you don’t need to worry about IE7 and earlier, array joining is one of the slowest ways to concatenatestrings. Use simple + and += operators instead,and avoid unnecessary intermediate strings.
• Backtracking is both a fundamental component of regex matching and a frequent source of regex inefficiency.
• Run away backtracking can cause a regex that usually finds matches quickly to run slowly or even crash your browser when applied to partially matching strings. Techniques for avoiding this problem include making adjacent tokens mutually exclusive, avoid ingnested quantifiers that allow matching the same part of a string more than one way, and eliminating needless backtracking by repurposing the
atomic nature of look ahead.
• A variety of techniques exist for improving regex efficiency by helping regexes find matches faster and spend less time considering nonmatching positions (see “More Ways to Improve Regular Expression Efficiency” on page 96).
• Regexes are not always the best tool for the job, especially when you are merely searching for literal strings.
• Although there are many ways to trim a string, using two simple regexes (one to remove leading whitespace and another for trailing whitespace) offers agood mix of brevity and cross-browser efficiency with varying string contents and lengths. Looping from the end of the string in search of the first nonwhitespace characters,or combining this technique with regexes in a hybrid approach, offers a good alternative that is less affected by over all string length.