说到trim,其实这真的让无数前端郁闷。比如在处理input框里内容的时候,都会需要处理input内容的左右空格。但让人郁闷的是,String里居然没有原生方法,而每个人的实现方法都会不一样,效率也各有不同。
但是,新版的ECMA-262里已经表示有此方法了:
ECMA-262(V5) 15.5.4.20 String.prototype.trim ( ) The following steps are taken: 1. Call CheckObjectCoercible passing the this value as its argument. 2. Let S be the result of calling ToString, giving it the this value as its argument. 3. Let T be a String value that is a copy of S with both leading and trailing white space removed. The definition of white space is the union of WhiteSpace and LineTerminator . 4. Return T. NOTE The trim function is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.
本文摘自http://www.cnblogs.com/snandy/archive/2011/02/26/1965866.html,只是经过我自己的整理了啦。
第一种:这种是大多数人都会写的,也是流传最多的代码了吧?
JavaScript代码 String.prototype.trim = function() { //return this.replace(/[(^/s+)(/s+$)]/g,"");//會把字符串中間的空白符也去掉 //return this.replace(/^/s+|/s+$/g,""); // return this.replace(/^/s+/g,"").replace(//s+$/g,""); }第二种:来自motools:
JavaScript代码 function trim(str){ return str.replace(/^(/s|/xA0)+|(/s|/xA0)+$/g, ''); }第三种:这是jQuery的,jquery的方法类似于第一种:
JavaScript代码 function trim(str){ return str.replace(/^(/s|/u00A0)+/,'').replace(/(/s|/u00A0)+$/,''); }
第四种是来自所摘博客中最写的:Steven Levithan 在进行性能测试后提出了在JS中执行速度最快的裁剪字符串方式,在处理长字符串时性能较好:
JavaScript代码 function trim(str){ str = str.replace(/^(/s|/u00A0)+/,''); for(var i=str.length-1; i>=0; i--){ if(//S/.test(str.charAt(i))){ str = str.substring(0, i+1); break; } } return str; }
博客中还写了这么一点,那就是Molliza Gecko 1.9.1引擎中还给String添加了trimLeft ,trimRight 方法。
这让我想起了PHP的代码,比如ltrim,rtrim,trim之类的