手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆

Javascript中各种trim的实现

首页 > Javascript >

说到trim,其实这真的让无数前端郁闷。比如在处理input框里内容的时候,都会需要处理input内容的左右空格。但让人郁闷的是,String里居然没有原生方法,而每个人的实现方法都会不一样,效率也各有不同。

但是,新版的ECMA-262里已经表示有此方法了:

  1. 15.5.4.20   String.prototype.trim ( )   
  2.   
  3. The following steps are taken:   
  4.   
  5. 1.   Call CheckObjectCoercible passing the this value as its argument.   
  6. 2.   Let S be the result of calling ToString, giving it the this value as its argument.   
  7. 3.   Let T be a String value that is a copy of S with both leading and trailing white space removed. The definition   
  8.      of white space is the union of  WhiteSpace and LineTerminator .   
  9. 4.   Return T.   
  10.   
  11. NOTE           The trim function is intentionally generic; it does not require that its this value be a String object. Therefore, it   
  12. 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代码
  1. String.prototype.trim = function() {  
  2.     //return this.replace(/[(^\s+)(\s+$)]/g,"");//會把字符串中間的空白符也去掉  
  3.     //return this.replace(/^\s+|\s+$/g,""); //  
  4.     return this.replace(/^\s+/g,"").replace(/\s+$/g,"");  
  5. }  

第二种:来自motools:

JavaScript代码
  1. function trim(str){  
  2.     return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, '');  
  3. }  

第三种:这是jQuery的,jquery的方法类似于第一种:

JavaScript代码
  1. function trim(str){  
  2.     return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');  
  3. }  

 

第四种是来自所摘博客中最写的:Steven Levithan 在进行性能测试后提出了在JS中执行速度最快的裁剪字符串方式,在处理长字符串时性能较好:

JavaScript代码
  1. function trim(str){  
  2.     str = str.replace(/^(\s|\u00A0)+/,'');  
  3.     for(var i=str.length-1; i>=0; i--){  
  4.         if(/\S/.test(str.charAt(i))){  
  5.             str = str.substring(0, i+1);  
  6.             break;  
  7.         }  
  8.     }  
  9.     return str;  
  10. }  

 

博客中还写了这么一点,那就是Molliza Gecko 1.9.1引擎中还给String添加了trimLefttrimRight 方法。

这让我想起了PHP的代码,比如ltrim,rtrim,trim之类的




本站采用创作共享版权协议, 要求署名、非商业和保持一致. 本站欢迎任何非商业应用的转载, 但须注明出自"易栈网-膘叔", 保留原始链接, 此外还必须标注原文标题和链接.

Tags: js, trim

« 上一篇 | 下一篇 »

只显示10条记录相关文章

javascipt的{}中逗号带来的困扰 (浏览: 29670, 评论: 6)
javascript实现函数重载的深入探索 (浏览: 23735, 评论: 0)
JS模拟FLASH效果 (浏览: 23227, 评论: 0)
IE和FF下JS的不同点(更详细) (浏览: 21749, 评论: 0)
JS 刷新页面的几个技巧 (浏览: 19745, 评论: 0)
对膘叔的文章感兴趣的朋友可以使用JS调用功能 (浏览: 19731, 评论: 0)
JS实现的街头霸王 (浏览: 18985, 评论: 1)
收藏的关于JS的一些文章 (浏览: 16941, 评论: 0)
JavaScript trim函数大赏 (浏览: 16872, 评论: 1)

发表评论

评论内容 (必填):