实现1
String.prototype.trim
= function ()
{ return this .replace(/^\s\s*/,
'' ).replace(/\s\s*$/,
'' ); } |
实现2
String.prototype.trim
= function ()
{ return this .replace(/^\s+/,
'' ).replace(/\s+$/,
'' ); } |
实现3
String.prototype.trim
= function ()
{ return this .substring(Math.max( this .search(/\S/),
0), this .search(/\S\s*$/)
+ 1); } |
实现4
String.prototype.trim
= function ()
{ return this .replace(/^\s+|\s+$/g,
'' ); } |
这个可以称得上实现2的简化版,就是利用候选操作符连接两个正则。但这样做就失去了浏览器优化的机会,比不上实现3。由于看来很优雅,许多类库都使用它,如JQuery与mootools
实现5
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 : '' ; } |
实现6
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; } |
实现7
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); } |