js实现trim函数

面试碰到了一道题,用js实现trim函数,用正则表达式替换可以实现,实现方式如下:

写成类的方法格式如下:(str.trim();)

   

     String.prototype.trim=function(){
      return this.replace(/(^\s*)|(\s*$)/g, "");
   }
   String.prototype.ltrim=function(){
      return this.replace(/(^\s*)/g,"");
   }
   String.prototype.rtrim=function(){
      return this.replace(/(\s*$)/g,"");
   }    

  

写成函数可以这样:(trim(str))

   function trim(str){ 
       return str.replace(/(^\s*)|(\s*$)/g, "");
   }
   function ltrim(str){ 
       return str.replace(/(^\s*)/g,"");
   }
   function rtrim(str){ 
       return str.replace(/(\s*$)/g,"");
   }

 

posted @ 2017-02-27 00:31  WananPr1st  阅读(478)  评论(0编辑  收藏  举报